1标沪、設定行高(line-height)
HTML:
<div class="parent">
<span class="child">你好</span>
</div>
CSS:
.parent{
width:200px;
height:200px;
border:1px solid red;
}
.child{
width:200px;
line-height: 200px;
text-align: center; //水平居中
display: inline-block;
}
重點:父容器高度和子元素line-height一樣的數值金句,內容中的行內元素就會垂直居中。
2、設置偽元素::before
HTML:
<div class="parent">
<div class="child"></div>
</div>
CSS:
.parent{
width:200px;
height: 200px;
border:1px solid red;
}
.parent::before{
content:'';
display: inline-block;
height:100%;
vertical-align: middle;
}
.child{
width:80px;
height: 100px;
background:red;
vertical-align: middle;
display: inline-block;
}
重點:給父元素添加一個偽元素::before军浆,讓這個偽元素的div高度為100%挡闰,這樣其他div就可垂直居中了,但div 本身就是塊級元素摄悯,而vertical-align是行內元素屬性,則需要修改為inline-block射众。
3晃财、absolute + transform
HTML:
<div class="parent">
<div class="child"></div>
</div>
CSS:
.parent{
width: 200px;
height: 200px;
background:#ddd;
position: relative;
}
.child{
width: 100px;
height: 50px;
background:green;
position: absolute;
top: 50%;
left:50%;
transform: translate(-50% , -50%);
}
重點:在父元素中設置相對定位position: relative典蜕,子元素設置絕對定位 position: absolute罗洗;top和left相對父元素的50%愉舔,與其搭配的 transform: translate(-50% , -50%)表示X軸和Y軸方向水平居中伙菜。
4. 設置絕對定位
HTML:
<div class="parent">
<div class="child"></div>
</div>
CSS:
.parent{
width:200px;
height: 200px;
position: relative;
border:1px solid red;
}
.child{
width:50px;
height: 50px;
position: absolute;
top:0;
left:0;
right:0;
bottom:0;
margin:auto;
background:red;
}
重點:子元素絕對定位position:absolute,父元素相對定位position: relative,將上下左右的數值都設置為0贩绕,同時margin:auto。絕對定位是會脫離文檔流的淑倾,這點要注意一下。
5娇哆、設置display:flex
HTML:
<div class="parent">
<div class="child"></div>
</div>
CSS:
.parent{
width: 200px;
height: 200px;
background: grey;
display: flex;
justify-content: center;
align-items: center;
}
.child{
width: 100px;
height: 50px;
background:green;
}
重點:給父元素設置display: flex布局,水平居中 justify-content: center治力,垂直居中align-items: center。
6宵统、absolute + calc
HTML:
<div class="parent">
<div class="child"></div>
</div>
CSS:
.parent{
width: 200px;
height: 200px;
border:1px solid black;
position: relative;
}
.child{
width: 100px;
height: 50px;
position: absolute;
background:red;
top: calc(50% - 25px); /*垂直居中 */
left:calc(50% - 50px); /*水平居中 */
}
重點:父元素position定位為relative覆获,子元素position定位為absolute榜田。水平居中同理锻梳。calc居中要減多少要結合到自己的寬高設置多少再進行計算箭券。
7. display:table-cell實現CSS垂直居中。
HTML:
<div class="parent">
<span class="child">你好</span>
</div>
CSS:
.parent{
width:200px;
height:200px;
border:1px solid red;
display: table;
}
.child{
background:red;
display: table-cell;
vertical-align: middle;
text-align: center;
}
重點:將父元素設置display:table辩块,子元素table-cell會自動撐滿父元素荆永。組合 display: table-cell废亭、vertical-align: middle具钥、text-align: center完成水平垂直居中豆村。