让一个元素居中显示,分为两种情况,一种是知道父元素以及自身大小,另外一种是都不知道大小;
知道元素尺寸 好办,让偏移量等于 父元素大小减去子元素大小除以2,具体为
.show_4{
position: absolute;
top:calc((200px - 100px) / 2);
left:calc((200px - 100px) /2);
}
calc css3的运算函数,可执行四则运算,用空格将运算符和变量隔开;
不知道元素尺寸 一般这种时候使用百分比
运用到css3的transform的translate()方法;
和弹性盒子的,主轴和交叉轴居中;
.box{
width: 100%;
height: 100%;
display: flex;
flex-wrap:wrap;
}
.box>div{
width: 200px;
border: 2px solid #DEB887;
height: 200px;
position: relative;
background-color: #7FFFD4;
}
.box>div>div{
width: 100px;
height: 100px;
background-color: #DEB887;
}
.show_0{
position: absolute;
top:50%;
left:50%;
transform: translate(-50%,-50%);
}
.show_1{
float: left;
margin-top:50%;
margin-left:50%;
transform: translate(-50%,-50%);
}
.show_2{
position: relative;
top:50%;
left:50%;
transform: translate(-50%,-50%);
}
.show_3{
position: relative;
}
.flex_0{
display: flex;
justify-content: center;
align-items: center;
}
效果