<!DOCTYPE html>
<html>
<head>
<style>
/* 方法1: 使用 margin 自动 */
.center {
width: 50%; /* 设置元素宽度 */
margin: auto; /* 自动计算左右外边距,使元素水平居中 */
}
/* 方法2: 使用 flexbox */
.container {
display: flex;
justify-content: center; /* 水平居中 */
}
/* 方法3: 使用 text-align (适用于内联元素或文本) */
.text-center {
text-align: center; /* 内联元素或文本内容水平居中 */
}
</style>
</head>
<body>
<!-- 方法1 -->
<div class="center">
<p>这是一个水平居中的 div。</p>
</div>
<!-- 方法2 -->
<div class="container">
<div>
<p>这是使用 flexbox 水平居中的 div。</p>
</div>
</div>
<!-- 方法3 -->
<div class="text-center">
<p>这是使用 text-align 居中的文本。</p>
</div>
</body>
</html>
方法1:通过设置 margin: auto
和指定宽度 (width
) 来实现块级元素的水平居中。margin: auto
会自动计算左右外边距,使元素在父容器中水平居中。
方法2:使用 CSS Flexbox 布局,通过 display: flex
和 justify-content: center
来实现子元素的水平居中。这种方式非常灵活,适合现代布局。
方法3:对于内联元素或文本内容,可以通过 text-align: center
来使其在父容器中水平居中。
上一篇:htmldiv居中代码
下一篇:图片居中怎么设置html
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站