<!DOCTYPE html>
<html>
<head>
<style>
/* 使用 Flexbox 实现 div 垂直居中 */
.container {
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
height: 100vh; /* 设置容器高度为视口高度 */
}
.centered-div {
width: 200px;
height: 200px;
background-color: lightblue;
}
</style>
</head>
<body>
<div class="container">
<div class="centered-div"></div>
</div>
</body>
</html>
.container
: 使用 display: flex
将容器设置为弹性盒子布局,justify-content: center
和 align-items: center
分别实现水平和垂直居中。height: 100vh
设置容器的高度为视口高度,确保内容可以在整个页面高度内居中。.centered-div
: 这是需要居中的子元素,设置了宽度和高度,并添加了背景颜色以便可视化效果。这种方式是现代浏览器中最常用的垂直居中方法之一,简洁且兼容性较好。
上一篇:css 折行
下一篇:css stroke
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站