CSS中内容居中的方法有很多种,具体取决于您想要居中的内容是什么类型的元素以及是在什么情况下居中,这篇文章主要为大家整理了常用的7种方法,感兴趣的小伙伴可以跟随小编一起学习一下
CSS中内容居中的方法有很多种,具体取决于您想要居中的内容是什么类型的元素以及是在什么情况下居中。以下是一些常见方法及代码示例:

1. 水平居中 - 文本或行内元素
使用 text-align 属性
1 2 3 |
.parent {
text-align: center; /* 子元素如果是内联或内联块元素,将会水平居中 */
}
|
1 2 3 4 5 |
<!-- HTML -->
<div class="parent">
<p>这是要居中的文本</p>
<img src="image.jpg" alt="图片">
</div>
|
2. 水平居中 - 块级元素
使用 margin: 0 auto
1 2 3 4 |
.child {
width: 300px; /* 需要给定一个宽度 */
margin: 0 auto; /* 左右外边距自动分配 */
}
|
1 2 3 4 |
<!-- HTML -->
<div class="parent">
<div class="child">这是要居中的块级元素</div>
</div>
|
3. 使用 Flexbox
1 2 3 4 |
.parent {
display: flex;
justify-content: center; /* 水平居中 */
}
|
1 2 3 4 |
<!-- HTML -->
<div class="parent">
<div class="child">这是要居中的任何元素</div>
</div>
|
4. 垂直居中 - 单行文本
使用 line-height
1 2 3 4 5 6 |
.parent {
height: 100px; /* 给定一个高度 */
}
.child {
line-height: 100px; /* 与父元素高度相同 */
}
|
1 2 3 4 |
<!-- HTML -->
<div class="parent">
<p class="child">这是单行垂直居中的文本</p>
</div>
|
5. 垂直居中 - 多行文本和块级元素
使用 Flexbox
1 2 3 4 5 |
.parent {
display: flex;
flex-direction: column;
justify-content: center; /* 垂直居中 */
}
|
1 2 3 4 |
<!-- HTML -->
<div class="parent">
<div class="child">这是多行垂直居中的内容</div>
</div>
|
6. 水平和垂直居中 - Flexbox 或 Grid
Flexbox 方式
1 2 3 4 5 |
.parent {
display: flex;
justify-content: center;
align-items: center; /* 垂直居中 */
}
|
1 2 3 4 |
<!-- HTML -->
<div class="parent">
<div class="child">水平和垂直居中</div>
</div>
|
Grid 方式
1 2 3 4 |
.parent {
display: grid;
place-items: center; /* 这相当于 align-items: center 和 justify-items: center 的简写 */
}
|
1 2 3 4 |
<!-- HTML -->
<div class="parent">
<div class="child">使用Grid布局实现水平和垂直居中</div>
</div>
|
7. 使用 position 和 transform
当元素尺寸未知时,可以使用此方法。
1 2 3 4 5 6 7 8 9 |
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
|
1 2 3 4 |
<!-- HTML -->
<div class="parent">
<div class="child">无论尺寸如何都会水平和垂直居中</div>
</div>
|
这些是CSS中最常用的居中方法,根据实际需求选择合适的策略。