属性允许你修改CSS视觉格式模型的坐标空间。使用它,元素可以被转换(translate)、旋转(rotate)、缩放(scale)、倾斜(skew)。
注意:只对block级元素生效!
.parent {
width: 400px;
height: 400px;
background: #00BCD4;
position: relative;
}
.child {
background: #9e9e9e;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.parent2 {
width: 400px;
height: 400px;
background: #00BCD4;
display: flex;
justify-content: center;
align-items: center;
}
.child2 {
background: #9e9e9e;
}
绝对居中定位
.parent3 {
position: relative;
width: 300px;
height: 300px;
background: #00BCD4;
}
// 绝对居中定位
.child3 {
width: 100px;
height: 100px;
margin: auto; //画重点
position: absolute;
background: #9e9e9e;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
// 负边距居中
.child3 {
width: 100px;
height: 100px;
position: absolute;
background: #9e9e9e;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
给父元素设一个合适的 font-size 的值,这个值的取值为该父元素的高度除以 1.14 得到的值,并且子元素必须 是一个 inline 或 inline-block 元素,需要加上 vertical-align: middle 属性。
.parent {
font-size: 175.4px; /*200/1.14 = 175.4*/
height: 200px;
text-align: center;
background: #00BCD4;
}
.child {
vertical-align: middle; /*画重点*/
background: #00BCD4;
display: inline-block; /*画重点*/
/*或display: inline;*/
font-size: 12px;
width: 50px;
height: 50px;
background-color: #00f;
}