左右布局
這個(gè)布局比較簡(jiǎn)單,直接使用float就可以實(shí)現(xiàn)
.left {
height: 100px;
border: 1px solid red;
float: left;
width: 50%;
/* 加上box-sizing是為了整個(gè)盒模型寬度計(jì)算方便 */
box-sizing: border-box;
}
.right {
height: 100px;
border: 1px solid green;
float: left;
width: 50%;
box-sizing: border-box;
}
左中右布局
- 實(shí)現(xiàn)1:使用左右布局的思路實(shí)現(xiàn)
.left {
height: 100px;
border: 1px solid red;
float: left;
width: 30%;
box-sizing: border-box;
}
.middle {
height: 100px;
border: 1px solid yellow;
float: left;
width: 30%;
box-sizing: border-box;
}
.right {
height: 100px;
border: 1px solid green;
float: left;
width: 30%;
box-sizing: border-box;
}
- 實(shí)現(xiàn)2:使用
inline-block
+text-align
實(shí)現(xiàn)
<div class="wrapper">
<div class="left">left</div>
<div class="middle">middle</div>
<div class="right">right</div>
</div>
<!-- font-size相關(guān)的代碼是為了去除inline-block元素之間的間隙 -->
.wrapper {
text-align: center;
font-size: 0px;
}
.left {
display:inline-block;
border: 1px solid red;
font-size: 14px;
}
.middle {
display:inline-block;
border: 1px solid yellow;
font-size: 14px;
}
.right {
display:inline-block;
border: 1px solid green;
font-size: 14px;
}
水平居中
- 實(shí)現(xiàn)1
div {
/* 必須指定寬度才能生效 */
width: 100px;
margin: 0 auto;
}
- 實(shí)現(xiàn)2:
inline-block
+text-align
,不在重復(fù) - 實(shí)現(xiàn)3:先用
margin
將div整個(gè)移動(dòng)到頁(yè)面寬度一般出,再往回移動(dòng)div寬度一半的距離即可實(shí)現(xiàn)水平居中
div {
height: 100px;
width: 100px;
border: 1px solid red;
margin-left: 50%;
position: relative;
transform: translateX(-50%);
}
垂直居中
- 實(shí)現(xiàn)1:設(shè)置
line-height
可以實(shí)現(xiàn)單行文字的垂直居中 - 實(shí)現(xiàn)2:使用
vertical-align
可以實(shí)現(xiàn)內(nèi)聯(lián)元素的垂直居中 - 實(shí)現(xiàn)3:多行文本可以通過(guò)調(diào)整
padding-top
和padding-bottom
實(shí)現(xiàn)垂直居中 - 實(shí)現(xiàn)4:和水平居中實(shí)現(xiàn)3是類似的思路,只不過(guò)用了絕對(duì)定位
<div class="wrapper">
<div class="inner"></div>
</div>
.wrapper {
height: 200px;
border: 1px solid red;
position: relative;
}
.inner {
height: 50px;
width: 50px;
border: 1px solid blue;
position: absolute;
top: 100px;
transform: translateY(-50%);
}
小技巧
- 一般使用了
display: inline-block
都要加上vertical-align: top
,避免出現(xiàn)奇怪的空隙 - 很多CSS效果都可以使用網(wǎng)上的generator來(lái)生成,更加方便