css元素居中之新老方法集合
css元素居中一直是比較熱門的需求,也屬於前端面試必考題目之一了,在這裡我們以flex佈局出現為劃分點分別介紹元素居中的新老方法集合:
1:利用基線對齊的方式,在父元素中增加一個偽元素,讓偽元素的行高與父元素的高度相同,需要居中的子元素必須是inline-block利用inline-block和父元素基線對齊的特性實現垂直居中,水平居中透過父元素設定text-align:center;實現水平居中
。parent{
height: 300px;
border: 1px red solid;
text-align: center;
}
。parent::after{
content: “”;
line-height: 300px;
}
。child{
background-color: brown;
display: inline-block;/*高度與基線對齊*/
}
2:利用表格元素格式實現,其中table-cell/inline/inline-block中可是設定vertical-align: middle;來實現垂直居中,如果使用table-cell展示還需設定其父元素寬度。
。wrapper{
display: table;
width: 100%;
}
。box{
width: 100%;
height:300px;
border: 1px solid red;
display: table-cell;
text-align: center;
vertical-align: middle; /*只有table-cell/inline/inline-block中有效*/
}
。box>div{
display: inline-block;
}
3:利用定位實現,其中需要利用transform:translate(-50%,-50%)設定水平位置和垂直位置的定位偏移,其中要注意居中元素不能設定外邊距,否則會造成偏移
。parent{
position: relative;
height: 300px;
border: 1px red solid;
}
。child{
position: absolute;
top: 50%;
left: 50%;
background-color: brown;
transform: translate(-50%,-50%);
/* margin: 100px 100px 20px 20px;定位是以外邊距為起點計算的,邊距影響佈局 */
}
在flex佈局和grid夠出現之後,元素居中就變得十分簡單了:
4:子元素中設定居中,在grid佈局和flex佈局中都可以使用該模式設定子元素居中
body{
height: 300px;
border:1px solid red;
display: grid;
}
div{
background: radial-gradient(black, transparent);
height: 50px;
width: 50px;
align-self: center;
justify-self: center;
}
5:在grid佈局和flex佈局中都可以使用父元素直接設定子元素居中的方式,而且透過justify-items: center;align-items: center; 和 justify-content: center; align-content: center; 兩種方式設定的居中效果一致,但是子元素的邊框大小是不一致的,可以自己嘗試
body{
height: 300px;
border:1px solid red;
display: grid;
/* display: flex; */
justify-items: center;
/* justify-content: center; */
/* align-items: center; */
align-content: center;
}
div{
background: radial-gradient(black, transparent);
}
6:最簡單的居中方式
body{
height: 300px;
border:1px solid red;
display: grid;
/* display: flex; */
}
div{
background: radial-gradient(red, transparent);
margin: auto;
}