CSS3 中使用 Flexbox 实现水平和垂直居中对齐
cssweb developmentfront end technology更新于 2025/12/16 9:16:17
要使用 Flexbox 实现水平和垂直居中对齐,请使用 CSS3 中的 align-items 属性。将 align-items 属性设置为 center。
以下是使用 Flexbox 实现水平和垂直居中对齐的代码 −
示例
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.h-container {
display: flex;
width: 300px;
height: 300px;
background-color: lightblue;
justify-content: center;
align-items: center;
border: 2px solid black;
}
.h-1 {
font-size: 30px;
width: 150px;
height: 150px;
background-color: red;
color: white;
border: 2px solid rgb(58, 2, 83);
}
</style>
</head>
<body>
<h2>Horizontal and vertical center alignment using flexbox</h2>
<div class="h-container">
<div class="h-1">Centered Div</div>
</div>
</body>
</html>
输出
上述代码将产生以下输出 −

相关文章
有用资源
css 参考教程 - 该教程包含有关 css 的更多信息:https://www.cainiaomax.com/css/

