9种方法:在CSS中实现水平垂直居中
最编程
2024-01-12 09:00:13
...
一、水平垂直居中 9 种方法汇总
有哪些方法?
父、子元素宽高未知时
- table-cell(使用表格样式)
- flex 布局(父级 justify-content: center 和 align-items: center 即可)
- absolute + transform(定位的上、左为 50%,translate 上、左负 50%)
- absolute + margin: auto(定位的上下左右为 0)
- Grid 网格布局
- 直接使用 table(改变结构实现,和第一条类似)
子元素固定宽高已知时(假设子元素宽高为 200px)
- absolute + calc(定位上、左负50%时减去子元素宽、高)
- absolute + 负margin(定位的上、左为 50%,margin 的上、左负子元素的一半)
父元素高度已知(假设为 400px),子元素宽高未知
- text-align + vertical-align
初始化测试代码
HTML 测试代码,默认父子元素宽高未知。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Demo</title>
</head>
<body>
<div class="parent">
<div class="children"></div>
</div>
<style>
.parent {
width: 100%;
height: 50%;
background-color: skyblue;
}
.children {
width: 20%;
height: 20%;
background-color: pink;
}
</style>
</body>
</html>
二、父、子元素宽高未知(6 种)
第一种:table-cell
.parent {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.children {
display: inline-block;
}
第二种:flex 布局(两种办法)
① 只设置父元素
.parent {
display: flex;
justify-content: center;
align-items: center;
}
② 同时设置父子元素
.parent {
display: flex;
}
.children {
align-self: center;
margin: auto;
}
第三种:absolute + transform
.parent {
position: relative;
}
.children {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
第四种:absolute + margin: auto
.parent {
position: relative;
}
.children {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
第五种:Grid 布局
.parent {
display: grid;
}
.children {
align-self: center;
justify-self: center;
}
第六种:直接使用 table(改变结构实现,和第一条类似)
HTML 代码
<table>
<tbody>
<tr>
<td class="parent">
<div class="children"></div>
</td>
</tr>
</tbody>
</table>
CSS 代码
.parent {
text-align: center;
}
.children {
display: inline-block;
}
三、子元素宽高已知(假设子元素宽高为 200px)
第一种:absolute + calc
.parent {
position: relative;
}
.children {
position: absolute;
top: calc(50% - 100px);
left: calc(50% - 100px);
}
第二种:absolute + 负 margin
.parent {
position: relative;
}
.children {
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
}
四、父元素高度已知(假设为 400px),子元素宽高未知
第一种:text-align + vertical-align
.parent {
text-align: center;
line-height: 400px;
}
.children {
display: inline-block;
vertical-align: middle;
line-height: initial;
}
上一篇: CSS 基础教学:诺禾与诺禾致源的解读
下一篇: 微信小程序实现一行文字水平居中