<!DOCTYPE html>
<html>
<head>
<style>
/* 设置父容器为 flex 布局,并使其子元素水平和垂直居中 */
.container {
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
height: 100vh; /* 使容器高度为视口高度 */
}
/* div 的样式 */
.centered-div {
width: 200px;
height: 200px;
background-color: lightblue;
}
</style>
</head>
<body>
<!-- 父容器 -->
<div class="container">
<!-- 需要居中的 div -->
<div class="centered-div"></div>
</div>
</body>
</html>
.container
是父容器,使用了 flex
布局,通过 justify-content: center
和 align-items: center
实现了子元素的水平和垂直居中。height: 100vh
使得父容器的高度等于视口高度,确保垂直居中有足够的空间。.centered-div
是需要居中的 div
,设置了宽度和高度以及背景颜色以便于观察效果。上一篇:html 特殊符号
下一篇:html5语义化标签
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站