个人博客:haichenyi.com。感谢关注
1. 目录
- 1–目录
- 2–行内元素水平居中
- 3–块级元素水平居中
2. 行内元素水平居中
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>CSS—元素居中</title><style>div {background-color: bisque;/* 水平居中,增加行内元素生效:文本等等 */text-align: center;}</style>
</head><body><div><p>哈哈哈哈</p></div>
</body></html>
3 块级元素水平居中
margin: 0 auto;
.margin0auto {width: 100px;height: 100px;background-color: aqua;/* 上下0px,左右自适应 */margin: 0 auto;}<div><div class="margin0auto"></div></div>
display: inline-block;和父容器的text-align: center;
<div style="text-align: center;"><!-- inline-block将块级元素设置为inline-block,然后利用父容器的text-align: center;属性使元素水平居中。这种方法适用于需要在一行中显示多个块级元素的情况。--><div style="display: inline-block; width: 200px;background-color: aquamarine;">块级元素1</div><div style="display: inline-block; width: 200px;background-color: aquamarine;">块级元素2</div><div style="display: inline-block; width: 200px;background-color: aquamarine;">块级元素3</div></div>
弹性布局(很重要)
<!-- 设置父容器的display: flex;和justify-content: center;属性,可以使子元素在父容器中水平居中。-->
<div style="display: flex; justify-content: center;"><div style="width: 200px;">这是一个使用Flexbox布局的块级元素</div>
</div>
Grid布局
<!-- 设置父容器的display: grid;和place-items: center;(或justify-items: center;和align-items: center;分别设置水平和垂直居中)属性 --><div style="display: grid; place-items: center;margin-top: 20px;"><div style="width: 200px;background-color: orange;">这是一个使用Grid布局的块级元素</div></div>
绝对定位和变换
<!-- 对于块级元素,还可以使用绝对定位和CSS变换(transform)来实现水平居中。1.将父容器设置为相对定位(position: relative;)2.子元素设置为绝对定位(position: absolute;)3.left: 50%;将子元素的左边缘移动到父容器的水平中心位置4.最后使用transform: translateX(-50%);将子元素自身的宽度的一半向左移动--><div style="position: relative; width: 100%; height: 200px;margin-top: 20px;"><divstyle="position: absolute; left: 50%; transform: translateX(-50%); width: 200px; background-color: cadetblue;">这是一个使用绝对定位和变换的块级元素</div></div>
没有什么好精炼的,根据不同的场景使用不同的方法即可。反正,我用的最多的就是弹性布局