常用居中方式

常用居中办法总结

水平居中:给 div 设置一个宽度,然后添加 margin:0auto 属性

1
2
3
4
div {
width: 200px;
margin: 0auto;
}

水平居中,利用 text-align:center 实现

1
2
3
4
5
6
7
8
9
10
11
12
.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 居中

1
2
3
4
5
6
7
8
9
10
11
div {
position: absolute;
width: 300px;
height: 300px;
margin: auto;
top: 0;
left: 0;
bottom: 0;
right: 0;
background-color: pink; /*方便看效果*/
}

水平垂直居中一

1
2
3
4
5
6
7
8
9
/*确定容器的宽高宽500高300的层设置层的外边距div{*/
position:absolute;/*绝对定位*/
width:500px;
height:300px;
top:50%;
left:50%;
margin:-150px00-250px;/*外边距为自身宽高的一半*/
background-color:pink;/*方便看效果*/
}

水平垂直居中二

1
2
3
4
5
6
7
8
9
10
/*未知容器的宽高,利用`transform`属性*/
div {
position: absolute; /*相对定位或绝对定位均可*/
width: 500px;
height: 300px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: pink; /*方便看效果*/
}

水平垂直居中三

1
2
3
4
5
6
7
8
9
10
11
/*利用flex布局实际使用时应考虑兼容性*/
.container {
display: flex;
align-items: center; /*垂直居中*/
justify-content: center; /*水平居中*/
}
.containerdiv {
width: 100px;
height: 100px;
background-color: pink; /*方便看效果*/
}

水平垂直居中四

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/*利用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;
}
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2015-2021 AURORA_ZXH
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信