如何居中 div?
- 水平居中:給 div 設(shè)置一個(gè)寬度,然后添加 margin:0 auto 屬性
div {
width: 200px;
margin: 0 auto;
}
- 水平居中,利用 text-align:center 實(shí)現(xiàn)
.container {
background: rgba(0, 0, 0, 0.5);
text-align: center;
font-size: 0;
}
.box {
display: inline-block;
width: 500px;
height: 400px;
background-color: pink;
}
- 讓絕對(duì)定位的 div 居中
div {
position: absolute;
width: 300px;
height: 300px;
margin: auto;
top: 0;
left: 0;
bottom: 0;
right: 0;
background-color: pink; /*方便看效果*/
}
- 水平垂直居中一
/*確定容器的寬高寬500高300的層設(shè)置層的外邊距div{*/
position: absolute;/*絕對(duì)定位*/
width: 500px;
height: 300px;
top: 50%;
left: 50%;
margin: -150px 0 0 -250px;/*外邊距為自身寬高的一半*/
background-color: pink;/*方便看效果*/
}
- 水平垂直居中二
/*未知容器的寬高,利用`transform`屬性*/
div {
position: absolute; /*相對(duì)定位或絕對(duì)定位均可*/
width: 500px;
height: 300px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: pink; /*方便看效果*/
}
- 水平垂直居中三
/*利用flex布局實(shí)際使用時(shí)應(yīng)考慮兼容性*/
.container {
display: flex;
align-items: center; /*垂直居中*/
justify-content: center; /*水平居中*/
}
.containerdiv {
width: 100px;
height: 100px;
background-color: pink; /*方便看效果*/
}
- 水平垂直居中四
/*利用text-align:center和vertical-align:middle屬性*/
.container {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: rgba(0, 0, 0, 0.5);
text-align: center;
font-size: 0;
white-space: nowrap;
overflow: auto;
}
.container::after {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
.box {
display: inline-block;
width: 500px;
height: 400px;
background-color: pink;
white-space: normal;
vertical-align: middle;
}
總結(jié):文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-759813.html
一般常見(jiàn)的幾種居中的方法有:
對(duì)于寬高固定的元素
(1)我們可以利用margin:0 auto來(lái)實(shí)現(xiàn)元素的水平居中。
(2)利用絕對(duì)定位,設(shè)置四個(gè)方向的值都為0,并將margin設(shè)置為auto,由于寬高固定,因此對(duì)應(yīng)方向?qū)崿F(xiàn)平分,可以實(shí)現(xiàn)水
平和垂直方向上的居中。
(3)利用絕對(duì)定位,先將元素的左上角通過(guò)top:50%和left:50%定位到頁(yè)面的中心,然后再通過(guò)margin負(fù)值來(lái)調(diào)整元素
的中心點(diǎn)到頁(yè)面的中心。
(4)利用絕對(duì)定位,先將元素的左上角通過(guò)top:50%和left:50%定位到頁(yè)面的中心,然后再通過(guò)translate來(lái)調(diào)整元素
的中心點(diǎn)到頁(yè)面的中心。
(5)使用flex布局,通過(guò)align-items:center和justify-content:center設(shè)置容器的垂直和水平方向上為居中對(duì)
齊,然后它的子元素也可以實(shí)現(xiàn)垂直和水平的居中。
對(duì)于寬高不定的元素,上面的后面兩種方法,可以實(shí)現(xiàn)元素的垂直和水平的居中。
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-759813.html
到了這里,關(guān)于CSS 如何居中 DIV的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!