水平垂直居中
居中之前
首先我們創建一對父子元素,併爲其設置好顏色大小備用
<div class="content">
<div class='incont'></div>
</div>
.content {
width: 250px;
height:250px;
margin: 50px;
padding: 25px;
background-color: #81b0db;
}
.incont {
width: 50px;
height: 50px;
background: aquamarine;
}
水平垂直居中
我們需要實現的效果圖如下:
方法一:absolute + 負margin
父級元素使用相對定位,子元素使用絕對定位,調整其相對於父元素的位置。要求是需要我們知道子元素的寬高。
.content {
position: relative;
}
.incont {
position: absolute;
top: 50%;
left: 50%;
margin-left: -25px;
margin-top: -25px;
}
方法二:absolute + margin auto
先設置各個方向的距離都是0,再將margin
設爲auto
.content {
position: relative;
}
.incont {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
方法三:absolute + calc
這種方法的使用和方法一一樣,只是這裏使用計算屬性表示出來,缺點也是需要知道子元素寬高:
.content {
position: relative;
}
.incont {
position: absolute;
top: calc(50% - 25px);
left: calc(50% - 25px);
}
缺點:IE9 以上才支持。
方法四:absolute + transform
這裏使用 transform
屬性對子元素進行偏移,好處是不需要知道子元素的寬高,直接用百分比表示即可:
.content {
position: relative;
}
.incont {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
缺點:IE9 以上才支持。
方法五:vertical-align
首先將子元素轉爲行內塊元素,然後通過父級元素的 text-aline
屬性將其水平居中,然後通過設置子元素的 vertical-align
屬性將其垂直居中。
.content {
background-color: #81b0db;
text-align: center;
line-height: 250px;/*和高度保持一致*/
}
.incont {
display: inline-block;
vertical-align: middle;
line-height: inherit;
}
下面列舉了 vertical-align
屬性的值,該屬性定義行內元素的基線相對於該元素所在行的基線的垂直對齊:
方法六:table-cell
我們知道,table 元素默認垂直居中,而通過 css 可以將元素轉爲 table 類型,代碼如下:
.content {
text-align: center;
display: table-cell;
vertical-align: middle;
}
.incont {
display: inline-block;
}
vertical-align
一般作用在內聯元素上,主要用於內聯元素間在垂直方向上的對齊。不過,vertical-align
同樣也可以作用於table-cell
元素,目的是爲了指定table-cell
中的內容在垂直方向上相對於table-cell
的對齊關係。
缺點:對於設置爲display: table-cell
的元素,對其設置margin
無效。
方法七:flex
通過彈性佈局,可以輕易的實現水平垂直居中,甚至都不需要操作子元素:
.content {
display: flex;
justify-content: center;/*水平居中*/
align-items: center;/*垂直居中*/
}
justify-content
屬性定義了項目在主軸上的對齊方式。
align-items
屬性定義項目在次軸上如何對齊。
對比小結
- PC端有兼容性要求,寬高固定,推薦absolute + 負margin
- PC端有兼容要求,寬高不固定,推薦css-table
- PC端無兼容性要求,推薦flex
- 移動端推薦使用flex