方法有很多,这里简述四种。
1.利用vertical-align进行居中。
2.用定位。
3.用弹性盒。
4.用网格布局。
一、vertical-align
给要居中元素添加标尺;或转为table-cell类型。
用标尺:
<div class="wrap">
<div class="box">Hello World!</div><span></span>
</div>
.wrap{
width: 300px;
height: 300px;
background: #ffff7f;
text-align: center;
}
.box{
display: inline-block;
background: #55ffff;
vertical-align: middle;
}
span{
display: inline-block;
width: 0;
height: 100%;
vertical-align: middle;
}
效果图:

用table-cell:
可以给父元素设为table,子元素设为table-cell(注释内容);也可以给父元素设为table-cell,子元素用margin水平居中;
在这里用的是父元素设置table-cell:
<div class="wrap">
<div class="box">Hello World!</div>
</div>
.wrap{
width: 300px;
height: 300px;
background: #ffff7f;
text-align: center;
display: table-cell;
vertical-align: middle;
/* display: table; */
}
.box{
background: #55ffff;
width: 100px;
margin: 0 auto;
/* display: table-cell;
vertical-align: middle; */
}
效果图:

二、定位
让子元素相对父元素绝对定位,用margin(注释内容)需有固定宽高;或translate进行居中。
<div class="wrap">
<div class="box">Hello World!</div>
</div>
.wrap{
width: 300px;
height: 300px;
background: #ffff7f;
position: relative;
}
.box{
background: #55ffff;
position: absolute;
/* width: 100px;
height: 20px;
left: 0;right: 0;top: 0;bottom: 0;
margin: auto; */
top: 50%;left: 50%;
transform: translate(-50%,-50%);
}
效果图同上。
三、弹性盒
父元素设为弹性盒,设水平垂直居中属性,也能达到该效果。
justify-content主轴方向对齐方式;align-items侧轴方向对齐方式。
CSS代码:
.wrap{
width: 300px;
height: 300px;
background: #ffff7f;
display: flex;
justify-content: center;
align-items: center;
}
.box{
background: #55ffff;
}
四、网格布局
所用属性:
place-items: 复合式写法
align-items: start | end | center | stretch; 垂直
justify-items: start | end | center | stretch; 水平
属性值:
start:对齐单元格的起始边缘。
end:对齐单元格的结束边缘。
center:单元格内部居中。
stretch:拉伸,占满单元格的整个宽度(默认值)。
CSS代码:
.wrap{
width: 300px;
height: 300px;
background: #ffff7f;
display: grid;
place-items: center center;
}
.box{
background: #55ffff;
}
本文介绍了使用CSS实现元素垂直居中的四种方法:利用vertical-align属性、定位、弹性盒及网格布局,每种方法都附有代码示例和效果说明。
254

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



