常見布局種類
1.左右布局
image.png
HTML代碼
<div class="left"></div>
<div class="right"></div>
CSS代碼
.left{
float: left;
height: 20px;
width: 30%;
background: red;
}
.right{
float: left;
height: 20px;
width: 70%;
background: green;
}
上面是自適應(yīng)的兩列布局:width擁百分比+float什乙;
image.png
HTML代碼
<div class="wrapper">
<div class="left"></div>
<div class="right"></div>
</div>
CSS代碼
.wrapper{
width: 500px;
}
.left{
float: left;
height: 20px;
width: 30%;
background: red;
}
.right{
float: left;
height: 20px;
width: 70%;
background: green;
}
上面是固定寬度的兩列布局:width:具體值/父級(jí)元素的寬度確定挽封,width+百分比;+float;
如果沒有加float的話臣镣,不能實(shí)現(xiàn)并排的兩列布局辅愿。
2.三列布局
image.png
HTML代碼
<div class="left">left</div>
<div class="center">center</div>
<div class="right">right</div>
CSS代碼
.left{
float: left;
height: 20px;
width: 30%;
background: red;
}
.center{
float: left;
height: 20px;
width: 10%;
background: yellow;
}
.right{
float: left;
height: 20px;
width: 60%;
background: green;
}
傳統(tǒng)的三列布局依托于float實(shí)現(xiàn)
image.png
HTML代碼
<div class="wrapper">
<div class="left">left</div>
<div class="center">center</div>
<div class="right">right</div>
</div>
CSS代碼
.wrapper{
position: relative;
}
.left{
position: absolute;
top: 0;
left: 0;
height: 20px;
width: 30%;
background: red;
}
.center{
margin-left: 30%;
height: 20px;
width: 10%;
background: yellow;
}
.right{
position: absolute;
top: 0;
right: 0;
height: 20px;
width: 60%;
background: green;
}
左右使用絕對(duì)定位來實(shí)現(xiàn),中間用margin實(shí)現(xiàn).
image.png
HTML代碼
<div class="left">left</div>
<div class="right">right</div>
<div class="center">center</div>
CSS代碼
.left{
float: left;
height: 20px;
width: 500px;
background: red;
}
.right{
float: right;
height: 20px;
width: 500px;
background: green;
}
.center{
margin-left: 500px;
margin-right: 500px;
height: 20px;
background: yellow;
}
左右模塊各自向左右浮動(dòng)忆某,并設(shè)置中間模塊的 margin 值使中間模塊寬度自適應(yīng)点待。
3.水平居中
image.png
塊級(jí)元素水平居中設(shè)置margin: 0 auto;
image.png
在父元素上設(shè)置 text-align: center 使文字/圖片水平居中。
text-align CSS屬性定義行內(nèi)內(nèi)容(例如文字)如何相對(duì)它的塊父元素對(duì)齊弃舒。text-align 并不控制塊元素自己的對(duì)齊癞埠,只控制它的行內(nèi)內(nèi)容的對(duì)齊状原。
4.垂直居中
設(shè)置上下pading相等實(shí)現(xiàn)居中
絕對(duì)定位加上負(fù)邊距實(shí)現(xiàn)居中
vertical-align: middle;實(shí)現(xiàn)居中
display: table-cell;實(shí)現(xiàn)居中