CSS水平垂直居中在Web开发中是一个比较常见的问题,这里介绍6种解决方案。下面逐个讲解:
CSS水平垂直居中在Web开发中是一个比较常见的问题,这里介绍6种解决方案。下面逐个讲解:
方案一:Flex布局
使用Flex布局可以很方便地实现水平和垂直居中。步骤如下:
- 父容器设置 display: flex;
- 父容器设置 justify-content: center; 和 align-items: center;
示例如下:
<div class="container">
<div class="box"></div>
</div>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 300px;
}
.box {
width: 100px;
height: 100px;
background-color: red;
}
方案二:绝对定位
使用绝对定位可以实现水平和垂直居中。步骤如下:
- 父容器相对定位,设置 position: relative;
- 子容器绝对定位,设置 position: absolute;
- 子容器设置 top: 50%; 和 left: 50%;
- 子容器设置 margin-top: -(子容器高度的一半); 和 margin-left: -(子容器宽度的一半);
示例如下:
<div class="container">
<div class="box"></div>
</div>
.container {
position: relative;
height: 300px;
}
.box {
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
margin-top: -50px;
margin-left: -50px;
background-color: red;
}
方案三:使用table-cell
使用table-cell可以实现水平和垂直居中。步骤如下:
- 父容器设置 display: table-cell;
- 父容器设置 vertical-align: middle;
- 子容器不加特殊样式即可水平和垂直居中。
示例如下:
<div class="container">
<div class="box"></div>
</div>
.container {
display: table-cell;
vertical-align: middle;
height: 300px;
text-align: center;
}
.box {
display: inline-block;
width: 100px;
height: 100px;
background-color: red;
}
方案四:使用transform
使用transform可以实现水平和垂直居中。步骤如下:
- 父容器相对定位,设置 position: relative;
- 子容器绝对定位,设置 position: absolute;
- 子容器设置 top: 50%; 和 left: 50%;
- 子容器设置 transform: translate(-50%, -50%);
示例如下:
<div class="container">
<div class="box"></div>
</div>
.container {
position: relative;
height: 300px;
}
.box {
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
background-color: red;
transform: translate(-50%, -50%);
}
方案五:使用grid布局
使用grid布局可以实现水平和垂直居中。步骤如下:
- 父容器设置 display: grid;
- 父容器设置 justify-content: center; 和 align-items: center;
- 子容器设置 justify-self: center; 和 align-self: center;
示例如下:
<div class="container">
<div class="box"></div>
</div>
.container {
display: grid;
justify-content: center;
align-items: center;
height: 300px;
}
.box {
width: 100px;
height: 100px;
background-color: red;
justify-self: center;
align-self: center;
}
方案六:使用line-height
使用line-height可以实现水平和垂直居中。步骤如下:
- 父容器设置指定高度;
- 子容器设置 line-height: 父容器高度;
示例如下:
<div class="container">
<div class="box">Hello World</div>
</div>
.container {
height: 300px;
text-align: center;
}
.box {
height: 300px;
line-height: 300px;
background-color: red;
display: inline-block;
}
以上就是6种CSS水平垂直居中的解决方案,具体使用时可以根据实际情况选择合适的方案。
编程基础网
本文标题为:CSS水平垂直居中解决方案(6种)
基础教程推荐
猜你喜欢
- JavaScript获得url查询参数的方法 2023-12-01
- HTML标签 2023-10-26
- layui table使用hide属性对列进行显示与隐藏 2022-10-20
- 手把手教你实现漂亮的Qt 登录界面 2024-01-09
- 总结JavaScript中布尔操作符||与&&的使用技巧 2023-12-01
- layui实现表格内下拉框 2023-11-10
- css中让元素隐藏的多种方法 2023-12-19
- Navigator sendBeacon页面关闭也能发送请求方法示例 2023-12-14
- jQuery实现的浮动层div浏览器居中显示效果 2024-01-07
- js中style.display=””无效的解决方法 2023-12-15
