实现一个元素在容器中水平垂直居中一直是前端开发过程中需要面对的一个难题,这里将总结一些常见的方法。
全面总结使用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实现水平垂直居中效果的方法
基础教程推荐
猜你喜欢
- php – 显示从数据库中提取的数据,基于html表单输入并在html页面中显示 2023-10-26
- 补码原码反码··原文:https://www.cnblogs.com/goahead--linux/p/10904701.html 2023-10-25
- 第10天:自适应高度 2022-11-07
- 全面了解CSS 2022-10-16
- ajax动态加载json数据并详细解析 2023-02-22
- 用CSS来实现一些动画在vue中使用之流星滑过(3) 2023-10-08
- ajax提交到java后台之后处理数据的实现 2023-02-01
- JavaScript数据在不同页面的传递(URL参数获取) 2023-08-12
- Vue——render函数 2023-10-08
- ajax实现改变状态和删除无刷新的实例 2023-02-14
