实现一个元素在容器中水平垂直居中一直是前端开发过程中需要面对的一个难题,这里将总结一些常见的方法。
全面总结使用CSS实现水平垂直居中效果的方法
实现一个元素在容器中水平垂直居中一直是前端开发过程中需要面对的一个难题,这里将总结一些常见的方法。
方法一:使用flex布局实现
flex布局可以很方便的实现一个元素在容器中居中,下面是实现水平垂直居中效果的代码:
.container {
display: flex;
justify-content: center;
align-items: center;
}
<div class="container">
<div class="box">This is a box.</div>
</div>
方法二:使用绝对定位实现
使用绝对定位需要知道容器的宽高,下面是实现水平垂直居中效果的代码:
.container {
position: relative;
}
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<div class="container">
<div class="box">This is a box.</div>
</div>
方法三:使用表格布局实现
表格布局虽然不常用,但可以很方便的实现一个元素在容器中居中,下面是实现水平垂直居中效果的代码:
.container {
display: table;
}
.box {
display: table-cell;
vertical-align: middle;
text-align: center;
}
<div class="container">
<div class="box">This is a box.</div>
</div>
方法四:使用line-height实现
当元素是一个行内元素时,我们可以使用line-height实现元素在容器中垂直居中,下面是实现垂直居中效果的代码:
.container {
height: 300px;
line-height: 300px;
text-align: center;
}
.box {
display: inline-block;
vertical-align: middle;
}
<div class="container">
<div class="box">This is a box.</div>
</div>
方法五:使用grid布局实现
grid布局可以很方便的实现一个元素在容器中居中,下面是实现水平垂直居中效果的代码:
.container {
display: grid;
place-items: center;
}
<div class="container">
<div class="box">This is a box.</div>
</div>
织梦狗教程
本文标题为:全面总结使用CSS实现水平垂直居中效果的方法


基础教程推荐
猜你喜欢
- gbk编码的网页如何设置加载utf-8编码的js文件 2022-11-04
- vue监听网络状态改变 2023-10-08
- Ajax实现局部刷新的方法实例 2023-02-23
- 重新认识表格和一个访问无障碍的数据表格例子 2022-10-16
- vue编译报错 a dependency to an entry point is not allowed 2023-10-08
- Vue 前端框架神器(前端必备) 2023-10-08
- 关于 javascript:Mapbox GeoJSON 通过本地 URL 加载:图标 2022-09-21
- ajax处理返回的json格式数据方法 2023-02-14
- HTML-CSS(四十)transfrom变形 2023-10-26
- vue开发之生命周期 2023-10-08