水平居中
1.行内元素
常用行内元素为a/img/input/span 等,标签内的HTML文本也属于此类。在块级父容器中让行内元素居中,只需使用 text-align: center;
这种方法可以让 inline/inline-block/inline-table/inline/flex 等类型的元素实现居中。
html结构:
<body>
<div class="txtCenter">
Hello World!!!
</div>
</body>
css样式:
<style>
div.txtCenter{
text-align:center;
}
</style>
2.块级元素
2.1 定宽块级元素
margin和width实现水平居中:元素通过指定宽度,并将两边的空外边距平均分配,可以使用 margin: auto;。
html结构:
<body>
<div class="center">
<p><b>注意: </b>使用 margin:auto 无法兼容 IE8, 除非 !DOCTYPE 已经声明。</p>
</div>
</body>
css样式:
<style>
div{
border:1px solid red;/*为了显示居中效果明显为 div 设置了边框*/
width:500px;/*定宽*/
margin:20px auto;/* margin-left 与 margin-right 设置为 auto */
}
</style>
注意: 如果没有设置 width 属性(或者设置 100%),居中对齐将不起作用。
2.2 不定宽块级元素
(1)相对定位法:通过给父元素设置 float,然后给父元素设置 position:relative 和 left:50%,子元素设置 position:relative 和 left:-50% 来实现水平居中。
缺点:设置了 position:relative,带来了一定的副作用。
html结构:
<body>
<div class="container">
<ul>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
</ul>
</div>
</body>
css样式:
<style>
.container{
float:left;
position:relative;
left:50%
}
.container ul{
list-style:none;
margin:0;
padding:0;
position:relative;
left:-50%;
}
.container li{
float:left;
display:inline;
margin-right:8px;
}
</style>
(2)强制内联:改变块级元素的 dispaly 为 inline 类型,然后使用 text-align:center 来实现居中效果。
缺点:将块级元素的display设置为inline,于是少了很多功能,比如盒子模型
HTML结构:
<body>
<div class="container">
<ul>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
</ul>
</div>
</body>
css样式:
<style>
.container{
text-align:center;
}
.container ul{
list-style:none;
margin:0;
padding:0;
display:inline;
}
.container li{
margin-right:8px;
display:inline;
}
</style>
(3)使用flexbox:要为元素设置flexbox布局,只需将display属性值设置为flex。
html结构:
<body>
<div class="container">
<ul>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
</ul>
</div>
</body>
css样式:
.container{
justify-content:center;
display:flex;
}
垂直居中
1.行内或类行内元素(比如文本和链接)
单行
对于单行行内或者文本元素,只需为它们添加等值的 padding-top 和 padding-bottom 就可以实现垂直居中:
html结构:
<body>
<div class="txtCenter">
Hello World!!!
</div>
</body>
css样式:
.txtCenter {
padding-top: 30px;
padding-bottom: 30px;
}
如果因为某些原因我们不能使用 padding 属性来实现垂直居中,而且已知文本不会换行,那么就可以让 line-height 和height相等,从而实现垂直居中:
css样式:
.txtCenter {
height: 100px;
line-height: 30px;
white-space: nowrap;
}
多行
对于多行文本,同样可以使用等值 padding-top 和 padding-bottom 的方式实现垂直居中。如果你在使用过程中发现这种方法没见效,那么你可以通过 CSS 为文本设置一个类似 table-cell 的父级容器,然后使用 vertical-align 属性实现垂直居中:
html结构:
<div class="parent">
<p class="child">很多行的文本</p>
</div>
css样式:
.parent {
display: table;
height: 300px;
width: 100%;
}
.child {
line-height: 2;
display: table-cell; /* 类似于表格中的单元格 */
vertical-align: middle;
}
2.块级元素
已知元素的高度
css样式:
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
height: 100px;
margin-top: -50px; /* account for padding and border if not using box-sizing: border-box; */
}