1.子绝父相定位 + margin: auto
2.子绝父相定位 + margin移动子元素自身高宽一半的值
3.子绝父相定位 + transform
4.flex弹性布局
目录
2.子绝父相定位 + margin移动子元素自身高宽一半的值
1.子绝父相定位 + margin: auto
父盒子设置相对定位,子盒子设置绝对定位,子盒子的上下左右定位值都为0,此时如果子盒子没有宽高,将会撑满整个父盒子,设置宽高之后给一个margin:auto属性,就能实现水平垂直居中
<style>
.father {
width: 300px;
height: 300px;
position: relative;
background-color: pink;
}
.son {
width: 100px;
height: 100px;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
background-color: skyblue;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
2.子绝父相定位 + margin移动子元素自身高宽一半的值
父盒子设置相对定位,子盒子设置绝对定位,然后将子盒子定位到父盒子top:50% left:50%的位置,此时子盒子并不在父盒子中心,而是偏右下,只需要将子盒子向上向右移动自身一半的值就可以实现水平垂直居中(注意:需要知道子盒子的宽高,父盒子宽高发生变化也不影响)
<style>
.father {
width: 500px;
height: 500px;
position: relative;
background-color: pink;
}
.son {
width: 100px;
height: 100px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
background-color: skyblue;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
3.子绝父相定位 + transform
这个方法可以说是第二种方法的升级版,父盒子设置相对定位,子盒子设置绝对定位,然后将子盒子定位到父盒子top:50% left:50%的位置,此时子盒子并不在父盒子中心,而是偏右下,只需要使用transform属性向上向下移动子盒子自身高宽的50%,就可以实现水平垂直居中(需要知道子盒子的宽高)
<style>
.father {
width: 300px;
height: 300px;
position: relative;
background-color: pink;
}
.son {
width: 100px;
height: 100px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background-color: skyblue;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
4.flex弹性布局
使用flex布局可以非常方便的实现水平垂直居中,实现flex弹性布局要给子元素的父元素设置displa:flex,通过justify-content: center和align-items: center实现水平垂直居中
<style>
.father {
width: 300px;
height: 300px;
display: flex;
justify-content: center;
align-items: center;
background-color: pink;
}
.son {
width: 100px;
height: 100px;
background-color: skyblue;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>