[英]Top and bottom fixed height with fluid height middle
我要問的是我用javascript做過的事情,但我確實想用css實現它(如果可能的話)
這是場景:
我有一個DIV元素,其高度為h px。 這個非常DIV元素也有3個子元素,它們也是DIV元素。 他們的目的如下:
第一個DIV元素是k px高度,並附加到父容器的頂部。 它的高度是恆定的。
第二個DIV元素是n px高度,並附加到父容器的底部。 它的高度是恆定的。
第三個DIV元素是h - (n + k) px。
我想要的是當我調整父div (這是一個浮動框)以自動保持第三個DIV元素h - (n + k)px時。
這可能只用css實現嗎?
是的使用calc()
函數:
為你的第3 div設置height
CSS屬性為:
height: calc(h - n - k);
如果您計划支持不支持calc()
瀏覽器,那么這是一種沒有它的方法。
重點是使用絕對定位,填充(與附加的頂部和底部元素相同的高度)和box-sizing:border-box;
:
html,body,.wrap { height: 100%; margin: 0; padding: 0; } div { box-sizing: border-box; } .wrap { position: relative; width: 50%; padding: 50px 0 80px; border: 5px solid tomato; } .one,.two { position: absolute; left: 0; width: 100%; border: 5px solid teal; } .one { height: 50px; top: 0; } .two { height: 80px; bottom: 0; } .three { height: 100%; background: gold; }
<div class="wrap"> <div class="one"></div> <div class="two"></div> <div class="three"></div> </div>
這是獎金沒有box-sizing
屬性,只有絕對定位:
html, body, .wrap { height: 100%; margin: 0; padding: 0; } .wrap { position: relative; width: 50%; } .one, .two, .three { position: absolute; left: 0; width: 100%; background: teal; } .one { height: 50px; top: 0; } .two { height: 80px; bottom: 0; } .three { top: 50px; bottom: 80px; background: gold; }
<div class="wrap"> <div class="one">... content 1 ...</div> <div class="two">... content 2 ...</div> <div class="three">...content 3 ...</div> </div>
一個替代calc()
是使用flexboxes 。 這些不會將高度耦合在一起,因此如果您更改了頁眉和頁腳的高度,則無需更新其他元素的CSS。
這是一個基本的例子:
$('button').on('click', function() { $('.container').height(function(i, v) { return v < 200 ? 250 : 150 }); })
.container { float:left; height:150px; width:300px; background-color:#000; /* set as a flex container laid out in a column (top to bottom) */ display:flex; flex-direction:column; } /* content div, flex auto fills the remaining height */ .container div { background-color:#0f0; flex:1 1 auto; } /* top red div, fixed at 50px */ .container div:first-child { flex:0 0 50px; background-color:#f00; } /* bottom blue div, fixed at 50px */ .container div:last-child { flex:0 0 50px; background-color:#00f; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <div class="container"> <div>Header</div> <div>Content</div> <div>Footer</div> </div> <div><button>Resize Container</button></div>
您可以使用calc
來實現此目的。 例如:
div {
height: calc(h - n - k);
}
如需進一步閱讀,請查看關於calc()
精彩教程: http : //webdesign.tutsplus.com/tutorials/calc-grids-are-the-best-grids--cms-22902
這是demo jsFiddle
HTML:
<div id="main">
<div id="a"></div>
<div id="b">Hello</div>
<div id="c"></div>
</div>
CSS:
#main{height: 100%;background:red;}
#a{height: 100px;background:blue;}
#c{height: 50px;background:green;}
#b{height: calc(100% - 150px});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.