今天在做开发任务的时候遇到了一个最基本的子集div在夫级div中水平垂直居中的问题,就总结了下我们经常用到的方法(此外由于自己能力问题,有误望指出批评)
一:通过定位来实现
1.如果子元素的大小是已知的,可以通过对子元素定位,并且margin值分别减去自己宽高的一半(上码)
<style>
.father {
width: 200px;
height: 200px;
border: 1px solid red;
position: relative;
}
.child {
width: 100px;
height: 100px;
background-color: #00BCBC;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
</style>
<body>
<div class="father">
<div class="child"></div>
</div>
</body>
效果图:
2.我们子元素的大小不明确的情况下,有两种实现方式
(1)用margin为auto实现
<style>
.father {
width: 200px;
height: 200px;
border: 1px solid red;
position: relative;
}
.child {
width: 100px;
height: 100px;
background-color: #00BCBC;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
</style>
<body>
<div class="father">
<div class="child"></div>
</div>
</body>
效果图:
(2)用到css3中的transform,但一定要注意兼容性
<style>
.father {
width: 200px;
height: 200px;
border: 1px solid red;
position: relative;
}
.child {
width: 100px;
height: 100px;
background-color: #00BCBC;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
<body>
<div class="father">
<div class="child"></div>
</div>
</body>
上图:
translate(x,y)会以本身的长宽作为参考,比如本身的长为100px,高为100px. 那填(50%,50%)就是向右,向下移动50px,添加负号就是向着相反的方向移动
二:通过dispaly: table-cell实现
该方法是通过将父元素转成表格样式,再利用表格的样式对子元素进行居中
<style>
.father {
width: 200px;
height: 200px;
border: 1px solid red;
display: table-cell;
vertical-align: middle;
}
.child {
width: 100px;
height: 100px;
background-color: #00BCBC;
margin: 0 auto;
}
</style>
<body>
<div class="father">
<div class="child"></div>
</div>
</body>
上图:
三:css3中的flex属性
存在兼容性,使用注意
<style>
.father {
width: 200px;
height: 200px;
border: 1px solid red;
display: flex;
justify-content: center;
align-items: center;
}
.child {
width: 100px;
height: 100px;
background-color: #00BCBC;
}
</style>
<body>
<div class="father">
<div class="child"></div>
</div>
</body>
上图:
说几句flexbox,他将夫级变成了“容器”,子集变成了“项目”,justify-content设置x轴上的对齐方式,align-items设置y轴上的对齐方式
css3的flexbox详细介绍:https://css-tricks.com/snippets/css/a-guide-to-flexbox/
希望有所帮助