css 水平垂直居中
原创大约 1 分钟
下面为公共代码:
<div class="box">
<div class="small">small</div>
</div>
.box {
width: 300px;
height: 300px;
background: #ddd;
}
.small {
background: red;
}
absolute
+ margin
实现
absolute
+ margin
第1种
.box {
position: relative;
}
.small {
position: absolute;
top: 50%;
left: 50%;
margin: -50px 0 0 -50px;
width: 100px;
height: 100px;
}
absolute
+ margin
第2种
.box {
position: relative;
}
.small {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
width: 100px;
height: 100px;
}
absolute
+ calc
实现
.box {
position: relative;
}
.small {
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
width: 100px;
height: 100px;
}
absolute
+ transform
实现
.box {
position: relative;
}
.small {
position: absolute;
top: 50%;
left: 50%;
/* transform: translate(-50%,-50%); */
transform: translate3d(-50%,-50%,0);
width: 100px;
height: 100px;
}
转行内元素
.box {
line-height: 300px;
text-align: center;
font-size: 0px;
}
.small {
padding: 6px 10px;
font-size: 16px;
display: inline-block;
vertical-align: middle;
line-height: 16px;
}
table-cell
.box {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.small {
padding: 6px 10px;
display: inline-block;
}
flex
flex
第1种
.box {
display: flex;
justify-content: center;
align-items: center;
}
flex
第2种
.box {
display: flex;
justify-content: center;
}
.small {
align-self: center;
}
grid
grid
第1种
.box {
display: grid;
justify-items: center;
align-items: center;
}
grid
第2种
.box {
display: grid;
}
.small {
justify-self: center;
align-self: center;
}
grid
第3种
.box {
display: grid;
justify-items: center;
}
.small {
align-self: center;
}
grid
第4种
.box {
display: grid;
align-items: center;
}
.small {
justify-self: center;
}