如何居中 div?
1. 水平居中:给 div 设置一个宽度,然后添加 margin:0auto 属性
div {
width: 200px;
margin: 0auto;
}
2. 水平居中,利用 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;
}
3. 让绝对定位的 div 居中
div {
position: absolute;
width: 300px;
height: 300px;
margin: auto;
top: 0;
left: 0;
bottom: 0;
right: 0;
background-color: pink; /*方便看效果*/
}
如何实现div水平垂直居中
水平垂直居中一
确定容器的宽高宽 500 高 300 的层设置层的外边距
div{
position:absolute; /*绝对定位 */
width:500px;
height:300px;
top:50%;
left:50%;
margin:-150px 00 -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;
}
总结:
一般常见的几种居中的方法有:
对于宽高固定的元素
- 我们可以利用 margin:0auto 来实现元素的水平居中。
- 利用绝对定位,设置四个方向的值都为 0,并将 margin 设置为 auto,由于宽高固定,
因此对应方向实现平分,可以实现水平和垂直方向上的居中。 - 利用绝对定位,先将元素的左上角通过 top:50%和 left:50%定位到页面的中心,然后再 通过 margin负值来调整元素的中心点到页面的中心。
- 利用绝对定位,先将元素的左上角通过 top:50%和 left:50%定位到页面的中心,然后再 通过 translate 来调整元素的中心点到页面的中心。
- 使用 flex 布局,通过 align-items:center 和 justify-content:center 设置容器的垂直和水平
方向上为居中对齐,然后它的子元素也可以实现垂直和水平的居中。
对于宽高不定的元素,上面的后面两种方法,可以实现元素的垂直和水平的居中。