使用 CSS 居中元素
C水平和垂直输入一个元素是一道很常见的面试题。假设有一个父元素包围着子元素:
<div class="parent">
<div class="child">hello world</div>
</div>
将元素与页面中心对齐的不同方法:
- 使用 Flex
- 使用网格
- 使用绝对位置
- 使用表格
- 使用书写模式
- 使用 Table 标签
- 使用 margin auto
1️⃣ 使用 Flex⭐️
Flexbox 控制项目的放置方式和空白空间的分布方式,这种方式需要 CSS 中为特定数量的元素设置神奇的数字。
根据 flex-direction,我们可能会使用 justify-content 或 align-items 进行必要的调整。
.parent {
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
2️⃣ 使用网格⭐️
CSS Grid 包含与 flexbox 几乎相同的对齐选项,因此我们可以在父级上使用它:
.parent {
height: 100vh;
display: grid;
place-items: center;
}
或者
.parent {
height: 100vh;
display: grid;
align-items: center;
justify-content: center;
}
3️⃣ 使用绝对位置
一个简单的老技巧,使用绝对位置。
.parent {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
4️⃣ 使用表格⎍
一种非常简单的方法,也是最早的方法之一(在过去,一切都是表格),就是使用表格单元格的行为和垂直对齐将元素置于容器的中心。
.parent {
width: 100vw;
height: 100vh;
display: table;
}
.child {
display: table-cell;
vertical-align: middle;
text-align: center;
}
5️⃣ 使用写作模式✍
writing-mode 可以改变文本的显示方向。例如,你可以使用 writing-mode 将文本的显示方向改为垂直方向。
.parent {
writing-mode: vertical-lr;
text-align: center;
height: 100vh;
}
.child {
writing-mode: horizontal-tb;
display: inline-block;
width: 100%;
}
6️⃣ 使用 Table 标签🏷
您也可以使用table
标签。
<table>
<tbody>
<tr>
<td class="father">
<div class="child">hello world</div>
</td>
</tr>
</tbody>
</table>
table {
height: 100vh;
width: 100%;
}
.father {
text-align: center;
}
7️⃣ 使用自动边距
在父级弹性元件上应用 margin-auto。
.parent {
display: flex;
height: 100vh;
}
.child {
margin: auto;
}
我使用的最佳方法是显示弹性(1)和显示网格(2)。
感谢您阅读本文。
希望您能从本文中有所收获。另外,如果您还有其他方法可以将元素置于页面中心,请告诉我😅。
请随时通过@suprabhasupi来联系我😋
文章来源:https://dev.to/suprabhasupi/center-element-using-css-13ib