苏飞论坛
标题: css-设置元素水平垂直居中 [打印本页]
作者: xyc 时间: 2021-7-2 14:37
标题: css-设置元素水平垂直居中
做项目都会遇到想要元素水平垂直居中的问题,今天我们就来说说实现元素水平垂直居中的几种方法。
1.position
html:
[HTML] 纯文本查看 复制代码
<div class="div">苏飞论坛</div>
(1).已知元素的宽和高
css:
[CSS] 纯文本查看 复制代码
.div {
background: #0C83F0;
width: 100px;
height: 100px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
color: #fff;
}
/* 或者 */
.div {
background: #0C83F0;
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin: -50px 0 0 -50px;
} (2).未知元素的宽和高
css:
[CSS] 纯文本查看 复制代码
.div {
color: red;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
} 2.flex
html:
[HTML] 纯文本查看 复制代码
<div class="wrap">
<div class="item">苏飞论坛</div>
</div>
css:
[CSS] 纯文本查看 复制代码
.wrap {
width: 100%;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.item {
color: #0C83F0;
} 3.使用伪类
html:
[HTML] 纯文本查看 复制代码
<div class="wrap">
<div class="item">苏飞论坛</div>
</div>
css:
[CSS] 纯文本查看 复制代码
.wrap {
width: 100%;
height: 100%;
background-color: #0C83F0;
text-align: center;
position: absolute;
top: 0;
left: 0;
}
.wrap:after {
display: inline-block;
content: '';
width: 0;
height: 100%;
vertical-align: middle;
}
.item {
color: #fff;
display: inline-block;
vertical-align: middle;
} 4.使用表格
html:
[HTML] 纯文本查看 复制代码
<div class="wrap">
<div class="item">苏飞论坛</div>
</div>
css:
[HTML] 纯文本查看 复制代码
.wrap {
width: 100%;
height: 100vh;
display: table;
}
.item {
color: red;
display: table-cell;
vertical-align: middle;
text-align: center;
}
以上就是我能想到的水平居中的方法了,希望可以帮助到大家!
作者: 范范 时间: 2021-7-2 15:59
支持楼主,加油
| 欢迎光临 苏飞论坛 (http://www.sufeinet.com/) |
Powered by Discuz! X3.4 |