友情提示: 看完本文章需要3分钟。
三种方式都可以在未知元素宽高的情况下使用。
一、DOM结构,很简单。
外层父元素father,内层子元素son。
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
所有结果图都是这样
二、上代码,一目了然。
1.首推 flex布局(一种布局方式,超级好用。不清楚这种布局的请看这里)
CSS代码:
.father{
display: flex;
align-items: center; /* 关键就是这两行 */
background: yellow;
width: 300px;
height: 300px;
}
.son{
background: green;
width: 100px;
height: 100px;
}
绝对定位+transform
css代码:
.father{
background: yellow;
position: relative;
width: 300px;
height: 300px;
}
.son{
position: absolute;
/* 关键是这2行 */
top: 50%; /* 自己头部在父元素的50%处 */
transform: translateY(-50%); /* 使自身上移50% */
background: green;
width: 100px;
height: 100px;
}
- 绝对定位+magin:auto
css代码:
.father{
background: yellow;
position: relative;
width: 300px;
height: 300px;
}
.son{
position: absolute;
/* 关键是这3行 /
top: 0;
bottom: 0;
margin: auto; / 在top0,bottom0的情况下,让自身的上下边距自适应 ,只能居中*/
background: green;
width: 100px;
height: 100px;
}