如何水平居中一个元素
1、行内元素水平居中
对inline
、inline-block
、inline-table
和inline-flex
元素水平居中都有效
html
<div class="parent">
<div class="child">Demo</div>
</div>
<style>
.parent{
text-align:center;
}
.child {
display: inline-block; //将其由块级元素改变为行内块元素
}
</style>
2、块级元素水平居中

2.1 margin-left
和margin-right
设置为auto
css
.child{
width: 100px; //确保该块级元素定宽
margin:0 auto;
}
2.2 table
+margin
css
.child {
display: table; //在表现上类似block元素,但是宽度为内容宽
margin: 0 auto;
}
2.3 absolute
+transform
- 父元素相对定位
- 子元素绝对定位
- 向右移动子元素,移动距离为父容器的一半
- 向左移动子元素的一半宽度
css
.child {
position:absolute;
left:50%; //parent宽度的50%
transform:translateX(-50%); //child宽度的50%
}
.parent {
position:relative;
}



2.4 使用flex
+justify-content
justify-content
用于设置弹性盒子元素在主轴(默认横轴)方向上的对齐方式
css
.parent {
display: flex;
justify-content:center;
}
2.5 使用flex
+margin
css
.parent {
display: flex;
}
.child {
margin:0 auto;
}
3、多块级元素水平居中
3.1 利用flex
布局
css
#container {
display: flex;
justify-content: center;
}
3.2 利用inline-block
text-align
定义行内内容(例如文字)如何相对它的块父元素对齐。text-align
并不控制块元素自己的对齐,只控制它的行内内容的对齐。
css
.container {
text-align: center;
}
.inline-block {
display: inline-block;
}
4、浮动元素水平居中
float
指定一个元素应沿其容器的左侧或右侧放置,允许文本和内联元素环绕它。该元素从网页的**正常流动(文档流)**中移除,但是仍然保持部分的流动性。
- 对于定宽的浮动元素,通过子元素设置
relative
+ 负margin
- 对于不定宽的浮动元素,父子容器都用相对定位
- 通用方法(不管是定宽还是不定宽):
flex
布局
4.1 定宽的非浮动元素

css
.child {
position:relative;
left:50%;
margin-left:-250px;
}
<div class="parent">
<span class="child" style="float: left;width: 500px;">我是要居中的浮动元素</span>
</div>
4.2 不定宽的浮动元素
css
<div class="box">
<p>我是浮动的</p>
<p>我也是居中的</p>
</div>
.box{
float:left;
position:relative;
left:50%;
}
p{
float:left;
position:relative;
right:50%;
}
4.3 通用办法flex布局
利用**弹性布局(flex)**的justify-content
属性,实现水平居中
css
.parent {
display:flex;
justify-content:center;
}
.chlid{
float: left;
width: 200px;//有无宽度不影响居中
}
<div class="parent">
<span class="chlid">我是要居中的浮动元素</span>
</div>
5、绝对定位元素水平居中
通过子元素绝对定位,外加margin: 0 auto
来实现
css
<div class="parent">
<div class="child">让绝对定位的元素水平居中对齐。</div>
</div>
.parent{
position:relative;
}
.child{
width: 200px;
height:100px;
background: yellow;
position: absolute; /*绝对定位*/
left: 0; /*此处不能省略,且为0*/
right: 0;/*此处不能省略,且为0*/
margin: 0 auto; /*水平居中*/
}