一、行内元素

对父元素设置text-align:center;

二、定宽块状元素

HTML

1
<div class="container">content</div>

CSS

1
2
3
4
5
.container{
width: 300px;
margin: 0 auto;
background-color: #000;
}

注:

  • 块状元素的宽度width为固定值,通过设置“左右margin”值为“auto”来实现居中.

三、不定宽块状元素

方法1.加入table标签

HTML

1
2
3
4
5
6
7
<table>
<tr>
<td>
<div class='wrap'>我要水平居中</div>
</td>
</tr>
</table>

CSS

1
2
3
table{
margin: 0 auto;
}

方法2.display:inline

HTML

1
2
3
4
5
6
7
<div class="wrap">
<ul>
<li>123</li>
<li>456</li>
<li>789</li>
</ul>
</div>

CSS

1
2
3
4
5
6
7
8
9
.wrap{
text-align: center;
}
.wrap ul{
display:inline;
}s
.wrap li{
display: inline;
}

注:

  • 设置元素显示类型为行内元素;
  • 可用于水平不定宽导航的水平居中

方法3.float元素水平居中

HTML

1
2
3
<div class="wrap">
<div class="content">content</div>
</div>

CSS

1
2
3
4
5
6
7
8
9
10
11
.wrap{
clear: both;
position: relative;
float: left;
left: 50%;
}
.content{
position: relative;
left: -50%;
background-color: red;
}

四、导航类“不定宽水平居中”

HTML

1
2
3
4
5
6
7
<header>
<nav>
<ul>
<li></li>
</ul>
</nav>
</header>

方法1.绝对定位、相对定位或translate()

CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
nav{
clear: both;
position:absolute;
left: 50%;
}
nav ul{
position: relative;
left: -50%;
list-style: none;
}
nav li{
float: left;
margin: 0 5px;
background-color: yellow;
}

注:

  • header默认宽度100%,把nav绝对定位,left:50%;然后里面的ul进行相对定位,left:-50%;在这点上绝对定位是办不到的,因为它把布局破坏掉了,容器宽度没有的情况下,它就面目全非,也无从谈起left:-50%。margin-left:-50%:也不小想行,它需要父容器宽度固定。
  • 使用translateX(-50%)同样可以达到效果,因为它也不需要父容器的宽度

方法3.Flexbox

CSS

1
2
3
4
5
6
ul{
list-style: none;
display: flex;
justify-content: center;
-webkit-justify-content: center;
}

注:

  • flexbox可以很轻松的解决元素的水平垂直居中问题;更详细资料:Flexbox

方法4.diaplay:inline/inline-block
CSS
```
nav ul{
text-align:center;
}
nav ul li{
display:inline-block;
}

注:

  • 把其中的每一项设置成为行内块元素,然后用文本居中的方式使其居中.