如何居中 div?
- 水平居中:給 div 設置一個寬度,然后添加 margin:0 auto 屬性
div {width: 200px;margin: 0 auto;
}
- 水平居中,利用 text-align:center 實現
.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;
}
- 讓絕對定位的 div 居中
div {position: absolute;width: 300px;height: 300px;margin: auto;top: 0;left: 0;bottom: 0;right: 0;background-color: pink; /*方便看效果*/
}
- 水平垂直居中一
/*確定容器的寬高寬500高300的層設置層的外邊距div{*/
position: absolute;/*絕對定位*/
width: 500px;
height: 300px;
top: 50%;
left: 50%;
margin: -150px 0 0 -250px;/*外邊距為自身寬高的一半*/
background-color: pink;/*方便看效果*/
}
- 水平垂直居中二
/*未知容器的寬高,利用`transform`屬性*/
div {position: absolute; /*相對定位或絕對定位均可*/width: 500px;height: 300px;top: 50%;left: 50%;transform: translate(-50%, -50%);background-color: pink; /*方便看效果*/
}
- 水平垂直居中三
/*利用flex布局實際使用時應考慮兼容性*/
.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;
}
總結:
一般常見的幾種居中的方法有:對于寬高固定的元素(1)我們可以利用margin:0 auto來實現元素的水平居中。(2)利用絕對定位,設置四個方向的值都為0,并將margin設置為auto,由于寬高固定,因此對應方向實現平分,可以實現水
平和垂直方向上的居中。(3)利用絕對定位,先將元素的左上角通過top:50%和left:50%定位到頁面的中心,然后再通過margin負值來調整元素
的中心點到頁面的中心。(4)利用絕對定位,先將元素的左上角通過top:50%和left:50%定位到頁面的中心,然后再通過translate來調整元素
的中心點到頁面的中心。(5)使用flex布局,通過align-items:center和justify-content:center設置容器的垂直和水平方向上為居中對
齊,然后它的子元素也可以實現垂直和水平的居中。對于寬高不定的元素,上面的后面兩種方法,可以實現元素的垂直和水平的居中。