1. 水平居中
1.1 行內元素
text-align: center;
1.2 塊級元素
margin: 0 auto;
這兩種方法都是用來水平居中的,前者是針對父元素進行設置而后者則是對子元素。
他們起作用的首要條件是子元素必須沒有被float
影響,否則一切都是無用功。
1.3 多于一個塊級元素:
1.3.1 子元素設置為inline-block
類型,同時父元素設置屬性text-align: center
;
.inline-block-center {
text-align: center;
}
.inline-block-center div {
display: inline-block;
text-align: left;
}
1.3.2 使用flex box
// 父元素
flex-center {
display: flex;
justify-content: center;
}
2.垂直居中
2.1 行內元素
2.1.1 單行行內元素
可以設置padding-top
,padding-bottom
如果無法使用padding
屬性,則將height
和line-height
設為相等也可以垂直居中。
2.1.2 多行行內元素
1)、可以將元素轉為table
樣式,再設置vertical-align:middle
;
.center-table {
display: table;
height: 250px;
background: white;
width: 240px;
margin: 20px;
}
.center-table p {
display: table-cell;
margin: 0;
background: black;
color: white;
padding: 20px;
border: 10px solid white;
vertical-align: middle;
}
2)、使用flex
布局
.flex-center-vertically {
display: flex;
justify-content: center;
flex-direction: column;
height: 400px;
}
這里要注意!!flex
布局要求父元素必須顯示設置height
3)、在容器中放置偽元素
使用vertical-align
使文本垂直對齊該偽元素。
<div class="ghost-center">
<p>I'm vertically centered multiple lines of text in a container. Centered with a ghost pseudo element</p>
</div>
.ghost-center {
position: relative;
}
.ghost-center::before {
content: " ";
display: inline-block;
height: 100%;
width: 1%;
vertical-align: middle;
}
2.2 塊級元素
2.2.1 已知高度
.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; */
}
2.2.2 元素是未知高度
1)、
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
2)、用flex
布局
.parent {
display: flex;
flex-direction: column;
justify-content: center;
}
3. 垂直和水平居中
3.1 固定大小元素
.parent {
position: relative;
}
.child {
width: 300px;
height: 100px;
padding: 20px;
position: absolute;
top: 50%;
left: 50%;
margin: -70px 0 0 -170px;
}
首先給父元素寫上positon:relative
,這么做是為了給子元素打上position:absolute
的時候不會被定位到外太空去。接下去,寫上子元素的height
和width
,這個似乎是必須的,某些瀏覽器在解析的時候如果沒有這2個值的話會出現意想不到的錯位。接著就是整個方法的核心,給子元素再打上top:50%;left:50%
以及margin-top
:一半的height
值的的負數;margin-left:
一半的width
值的負數。整理一下之后,可能你會給你的子元素寫上這樣的css(當然,父元素也要先寫上width
和height
)
3.2 未知大小元素
如果當前元素大小未知,可以使用translate將元素在x和y兩個方向反向偏移自身的50%的大小,使其居中顯示
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
3.3 使用flex居中
.parent {
display: flex;
justify-content: center;
align-items: center;
}
3.4 grid居中
body, html {
height: 100%;
display: grid;
}
span { /* thing to center */
margin: auto;
}