css的div盒子居于页面正中间
1. HTML代码
<body>
<div class="father">
<div class="son">son盒子</div>
</div>
</body>
2. 实现效果
3. 实现方法
方法一:
```css
<style>
*{
margin: 0;
padding: 0;
}
.father{
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
top: 50%;
left: 50%;
transform: translate(0, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
display: flex; /* son盒子绝对定位 */
justify-content: center;/* son盒子水平居中 */
align-items: center;/* son盒子垂直居中 */
text-align: center;/* 在父级元素设置这个样式可以让里面的文字水平居中 */
}
.son{
width: 100px;
height: 100px;
background-color: purple;
line-height: 100px;/* 利用这个样式设置line-height等于父级元素的高度可以让文字垂直居中 */
}
</style>
方法二:
<style>
.father {
overflow: hidden;
width: 300px;
height: 300px;
margin: 100px auto;
background-color: pink;
text-align: center;
}
.son {
width: 200px;
height: 200px;
margin: 50px;
background-color: purple;
line-height: 200px;
color: #fff;
}
</style>