你可以只設置body
padding-top
到頭部的高度,並添加top: 0
到頭部的CSS。
body {
padding-top: 50px;
}
.header{
position: fixed;
top: 0;
}
.header, .body, .footer {
width:100%;
height:200px;
border:1px solid blue;
}
.header {height: 50px;}
.body {text-align:center;}
.footer {}
.center-horiz{width:200px;height:100px;border:1px solid #666; display: inline-block;}
<div class="header">My menu</div>
<div class="body">some text2
<br>
<div class="center-horiz">div centered horizontally</div>
</div>
<div class="footer">some text3</div>
或者你可以給.body
頭的高度的margin-top
。
.header{
position: fixed;
top: 0;
}
.header, .body, .footer {
width:100%;
height:200px;
border:1px solid blue;
}
.header {height: 50px;}
.body {
margin-top: 50px;
}
.body {text-align:center;}
.footer {}
.center-horiz{width:200px;height:100px;border:1px solid #666; display: inline-block;}
<div class="header">My menu</div>
<div class="body">some text2
<br>
<div class="center-horiz">div centered horizontally</div>
</div>
<div class="footer">some text3</div>
使用JavaScript得到DOM頭高度加載並設置.body
元素的margin-top
。 (這也適用於頭部的動態高度)
document.addEventListener('DOMContentLoaded', function(e) {
var headerElement = document.querySelector('.header');
var bodyElement = document.querySelector('.body');
bodyElement.style.marginTop = headerElement.getBoundingClientRect().height + 'px';
})
.header{
position: fixed;
top: 0;
}
.header, .body, .footer {
width:100%;
height:200px;
border:1px solid blue;
}
.header {height: 50px;}
.body {text-align:center;}
.footer {}
.center-horiz{width:200px;height:100px;border:1px solid #666; display: inline-block;}
<div class="header">My menu</div>
<div class="body">some text2
<br>
<div class="center-horiz">div centered horizontally</div>
</div>
<div class="footer">some text3</div>
注:如果頭的和動態的高度上的窗口大小調整變化,你必須添加一個
resize
監聽器,設置在調整大小保證金。
好多久你打算更改標題的高度? –
@WilliamRobinson不經常,但我不想離開的驚喜在未來開發。 –