html内容:
<div class="box">
<div class="con"></div>
</div>
CSS内容:
方法一:text-align: center; vertical-align: middle;
.box {
border:1px solid red;
width:500px;
height:200px;
line-height:200px;
text-align: center;
}
.con {
border:1px solid green;
width:50px;
height:50px;
display:inline-block;
vertical-align: middle;
}
方法二:知道子元素宽高的条件下,
使用 子元素添加 top:父元素height/2 或者50%,left:width/2 或者50%,
有三种写法:
1.margin-top:height/2; margin-left: -width/2;
2.transform: translate(-50%, -50%);子元素宽高的50%
3.transform: translate(-width/2px, -height/2px);
或者直接使用top: calc(50% - 子元素height/2); left:calc(50% - 子元素width/2);
.box {
border:1px solid red;
width:500px;
height:200px;
position:relative;
}
.con {
border:1px solid green;
width:50px;
height:50px;
position:absolute;
left:50%;
top:50%;
margin-top:-25px;
margin-left: -25px;
}
方法三:不知道子标签宽高的条件下,使用transform: translate(-50%, -50%);
.box {
border:1px solid red;
width:500px;
height:200px;
position:relative;
}
.con {
border:1px solid green;
position:absolute;
top:50%;
left:50%;
transform: translate(-50%, -50%);
}
方法四:display:flex;
父级一定给高度,不然align-items: center;无效
.box {
display:flex;
justify-content: center;
align-items: center;
height:400px;
background: blue;
}
.con {
width:100px;
height:100px;
background: red;
}
方法五:display:table-cell;
.box{
width:500px; height:300px;
border:1px solid red;
display: table-cell;
text-align:center;
vertical-align:middle;
}
.con{
width:100px;
height:100px;
}
网友评论