一、讓元素水平居中
1.想要一個(gè)塊級(jí)元素在其包含元素內(nèi)居中,可以將此塊級(jí)元素的左、右外邊距的值設(shè)為auto。
html代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="box1">
<p class="box2">
This is a paragraph with a fixed width,
and left and right margins set to auto,
So it's centered.
</p>
</div>
</body>
</html>
CSS代碼:
.box1 {
background-color:pink;
width:400px;
height:100px;
}
.box2 {
background-color:green;
width:300px;
height:50px;
margin-left:auto;
margin-right:auto;
}
Output:

output1.png
2.想要一個(gè)inline元素、或inline-block元素在其包含元素內(nèi)居中,可以將其被包含元素設(shè)置為 text-align:center。
html代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="box1">
<p class="box2">
This is a paragraph with a fixed width,
and left and right margins set to auto,
So it's centered.<br>
</p>
<p class="box3"> <a href="hicc.me">想了解更多請(qǐng)點(diǎn)擊。</a>
</p>
</div>
</body>
</html>
CSS代碼:
.box1 {
background-color:pink;
width:500px;
height:200px;
}
.box2 {
background-color:green;
width:450px;
height:80px;
margin-left:auto;
margin-right:auto;
}
.box3 {
width:400px;
background-color:blue;
height:80px;
text-align:center;
}
a {
background-color:yellow;
}
Output:

output2.png
二、讓元素垂直居中
在transform: translateY的幫助下我們可以使用三行CSS代碼讓任何甚至不知道高度的元素垂直居中。CSS的transform屬性常用來旋轉(zhuǎn)和縮放元素,現(xiàn)在我們可以使用它的translateY函數(shù)垂直對(duì)齊元素。
垂直居中通常的做法是使用絕對(duì)定位或者設(shè)置行高,但是這兩種方案的弊端是要么需要你知道元素的高度,要么只能作用于單行文本(注:inline或者inline-block元素)。
代碼如下:
.element {
position: relative;
top: 50%;
transform: translateY(-50%);
}