有兩種情況:
image.png
如何實現(xiàn)
定寬
width: 1000px; 或 max-width: 1000px;
水平居中
margin-left: auto; margin-right: auto;
width
和max-width
的區(qū)別
width:600px
表示寫定寬度鳍烁,容器的寬度一定為600px劫哼,
max-width:600px
表示最大寬度為600px霸株,當(dāng)瀏覽器的寬度大于600px容器的寬度為600px术辐,當(dāng)瀏覽器的寬度小于600px時续镇,容器的寬度則變?yōu)橛蓛?nèi)容撐開的寬度,不再是600px竞阐。
一欄布局
<style>
.layout{
/* width: 960px; */
max-width: 960px;
margin: 0 auto;
}
#header{
height: 60px;
background: red;
}
#content{
height: 400px;
background: blue;
}
#footer{
height: 50px;
background: yellow;
}
</style>
<div class="layout">
<div id="header">頭部</div>
<div id="content">內(nèi)容</div>
<div id="footer">尾部</div>
</div>
優(yōu)化
直接把class='layout'加在需要的div上,省標(biāo)簽。便于控制局部暑劝。
<style>
.layout{
width: 960px;
margin: 0 auto;
}
#header{
height: 60px;
background: red;
}
#content{
height: 400px;
background: blue;
}
#footer{
height: 50px;
background: yellow;
}
</style>
<div id="header" class="layout">頭部</div>
<div id="content" class="layout">內(nèi)容</div>
<div id="footer" class="layout">尾部</div>
一欄布局(通欄)
<style>
.layout{
width: 960px;
margin: 0 auto;
}
#header{
height: 60px;
background: red;
}
#content{
height: 400px;
background: blue;
}
#footer{
height: 50px;
background: yellow;
}
</style>
<div id="header">
<div class="layout">頭部</div>
</div>
<div id="content" class="layout">內(nèi)容</div>
<div id="footer">
<div class="layout">尾部</div>
</div>
缺陷:當(dāng)瀏覽器大小小于.layout設(shè)置的寬度時骆莹,會出現(xiàn)content 的溢出。如圖
image.png
優(yōu)化
給 body 設(shè)置min-width 去掉滾動背景色 bug
<style>
.layout{
width: 960px;
margin: 0 auto;
}
body{
min-width: 960px;
}
#header{
height: 60px;
background: red;
}
#content{
height: 400px;
background: blue;
}
#footer{
height: 50px;
background: yellow;
}
</style>
<div id="header">
<div class="layout">頭部</div>
</div>
<div id="content" class="layout">內(nèi)容</div>
<div id="footer">
<div class="layout">尾部</div>
</div>