HTML5+CSS3-基础09-水平&垂直居中
直接上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.father {
width: 1000px;
height: 1000px;
background-color:green;
position: relative;
}
.son {
width: 150px;
height: 150px;
background-color: skyblue;
line-height: 150px;
text-align: center;
color: #fff;
}
/* 定位1 (需要知道盒子的自身高度和宽度)*/
/* .son {
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
} */
/* 定位2 (盒子需要高度和宽度)*/
/* .son{
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
} */
/* 定位3 (兼容性不好)*/
/* .son{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
} */
/* 4.利用display:flex布局 */
/* .father{
display: flex;
align-items: center;
justify-content: center;
} */
/* 5.需要父盒子有固定宽高 */
.father{
display: table-cell;
vertical-align: middle;
text-align: center;
}
.son{
display: inline-block;
}
</style>
</head>
<body>
<div class="father" id="father">
<div class="son" id="son">水平/垂直居中</div>
</div>
<!-- js方法 -->
<script>
// winW = father.offsetWidth;
// winH = father.offsetHeight;
// sonW = son.offsetWidth;
// sonH = son.offsetHeight;
// son.style.position = "absolute";
// son.style.left = (winW - sonW) / 2 + "px";
// son.style.top = (winH - sonH) / 2 + "px";
</script>
</body>
</html>
内容仅供学习参考,若有错误欢迎大家指正----WUCASE