css水平居中

DOME

在 CSS 中,如何让一个元素水平居中,即如何实现水平居中布局?长话短说,让我们一起来看下吧。

一、实现方式

1
2
3
<div class="parent">
<div class="child">DOME</div>
</div>

1. 行内元素特性 inline-block + text-align

1
2
3
4
5
6
7
.parent {
text-align: center;
}
.child {
display: inline-block;
text-align: center;
}

2. 块级表格 table + margin

1
2
3
4
.child {
display: table;
margin: 0 auto;
}

3. 绝对定位 absolute + transform

1
2
3
4
5
6
7
8
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%;
transform: translateX(-50%); /* 相对自身 */
}

3. flex

1. flex + justify-content
1
2
3
4
.parent {
display: flex;
justify-content: center;
}
2. flex + margin
1
2
3
4
5
6
.parent {
display: flex;
}
.child {
margin: 0 auto;
}

4. gird

1. gird + justify-content
1
2
3
4
.parent {
display: gird;
justify-self: center;
}
2. gird + margin
1
2
3
4
5
6
.parent {
display: gird;
}
.child {
margin: 0 auto;
}

二、补充说明

以上均是考虑到页面内容不定宽的情况。事实上如果元素的子元素宽度确定,可以直接用margin: 0 auto;使其水平居中。

实例页面

-------------本文结束感谢您的阅读-------------
0%