页面结构为:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>水平垂直居中</title>
</head>
<body>
<div class='content'></div>
</body>
</html>
未知元素宽高的情况下:
1.
.content{
width: 100px;
height: 100px;
background-color: rebeccapurple;
position: absolute;
margin: auto;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
2.
.content{
width: 100px;
height: 100px;
background-color: rebeccapurple;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50% );
}
知道元素的宽高
.content{
width: 100px;
height: 100px;
background-color: rebeccapurple;
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}
知道容器的宽高
1.
<!-- 改变页面结构 -->
<div class='box'>
<div class='content'></div>
</div>
.box {
width: 100%;
display: -webkit-flex;
justify-content: center;
align-items: center;
height: 200px;
background-color: antiquewhite;
}
.content{
width: 100px;
height: 100px;
background-color: rebeccapurple;
}
2.
<!-- 改变页面结构 -->
<div class='box'>
<div class='div-table'>
<div class='content'></div>
</div>
</div>
.box {
width: 100%;
height: 200px;
display: table;
background-color: antiquewhite;
}
.div-table {
display: table-cell;
vertical-align: middle;
}
.content {
width: 100px;
height: 100px;
margin: 0 auto;
background-color: rebeccapurple;
}
本文介绍了多种在网页设计中实现元素水平垂直居中的方法,包括未知和已知元素宽高情况下的CSS定位技巧,以及利用容器尺寸进行精确布局的策略。
834

被折叠的 条评论
为什么被折叠?



