假设有如下结构的代码:
<div id="app">
<div id="content"></div>
</div>
#app {
width: 100px;
height: 100px;
border: 1px solid red;
}
#content {
width: 50px;
height: 50px;
background-color: red;
}
flex布局
#app {
display: flex;
justify-content: center;
align-items: center;
}
绝对定位+CSS3translate
#app {
position: relative;
}
#content {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
相对定位+translateY+margin
#content {
position: relative;
top:50%;
transform:translateY(-50%);
background-color: red;
margin: 0 auto;
}
绝对定位+margin
content如果没有设置高度或者没有会自动最大尺寸,绝对定位的值只要设置成相等即可,不一定非要0
#app {
position: relative;
}
#content {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
相对定位+translate
#app {
position: relative;
}
#content {
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}