最近想转行前端 面试时被教育了 ,关于css设置水平垂直居中这个应该是基础的基础了 回答不上来确实还是有点尴尬的 我第一时间就想到了 最简单的 针对 div设置 margin 0 auto ; 实操一下
<body>
<div class="box">
<div class="item">居中</div>
</div>
</body>
<style>
.box{
background-color: aquamarine;
width: 300px;
height: 300px;
}
.item{
width: 100px;
height: 100px;
margin: 0 auto;
background-color: bisque;
}
</style>
以上代码运行后可以看到 只进行了水平居中,
如果要继续达成垂直水平居中 可以在这个基础上设置相对定位 top 50% 并向上偏移元素一半的高度 代码如下 注意因为父元素是个div 给子元素设置margin-top时父元素会一起上移 所以需要给父元素设置一个padding-top 或者通过 下面的 translate来实现
.box {
width: 300px;
height: 300px;
padding-top: 1px;
margin: 0;
background-color: blue;
}
.item {
width: 100px;
height: 100px;
background: orange;
margin: 0 auto;
/*水平居中*/
position: relative;
/*设置position*/
top: 50%;
margin-top: -50px;/*元素高度的一半 */
}
效果如图
还有其他方法 比如 使用绝对定位方式来实现垂直水平居中
<body>
<div class="box">
<div class="item">居中</div>
</div>
</body>
<style>
.box {
background-color: aquamarine;
width: 300px;
height: 300px;
position: relative;
}
.item {
position: absolute;
background-color: blanchedalmond;
text-align: center;
width: 100px;
height: 100px;
top: 50%;
left: 50%;
margin-top: -50px;
/*高度的一半*/
margin-left: -50px;
/*宽度的一半*/
}
</style>
效果如图,但是就像代码里写的一样 这种需要提前知道具体元素大小 然后通过搜索引擎看到 现在css3.0 可以使用 设置transform来替换 margin的设置 translate主要是设置元素的2d偏移量 可以针对元素自身的百分比设置 所以完成了 水平垂直居中
.item {
position: absolute;
background-color: blanchedalmond;
text-align: center;
width: 100px;
height: 100px;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
/* margin-top: -50px; */
/*高度的一半*/
/* margin-left: -50px; */
/*宽度的一半*/
}
还可以使用弹性盒子 flex 布局 来实现 这个使用应该是比较多的 代码如下
.box {
display: flex;
background-color: aquamarine;
width: 300px;
height: 300px;
align-items: center;
justify-content: center;
}
.item {
width: 100px;
height: 100px;
background: orange;
}
效果如下
不知不觉就要下班了 果然实际操作一下印象还是非常深刻的 总结一下 css垂直水平居中可以通过 相对定位 绝对定位 弹性盒子 进行水平垂直居中 当然还有很多其他实现方式 这里只实际操作了这几个方法。