思路:父元素position: relative; 子元素通过position: absolute;定位到居中。
结构与基础css(父元素position: relative;)
<div class="app">
<div class="box">box</div>
</div>
.app{
height: 300px;
background-color: gray;
position: relative;
}
.box{
width: 100px;
height: 100px;
background-color: red;
}
方法一
.box{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 0;
top: 50%;
margin-top: -50px;
}
方法二
.box{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%);
}
方法三
.box{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 0;
top: calc(50% - 50px);
}
方法四
.box{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 0;
top: 0;
bottom: 0;
margin: auto 0;
}
方法五
利用flex布局,简单快速实现
.app{
display: flex;
align-items: center;
}