居中也是 css 中使用頻率非常高的知識點制妄,看下面的例題两蟀。
<style>
.wp {
border: 1px solid orange;
width: 300px;
height: 300px;
}
.box {
background: green;
width: 100px;
height: 100px;
}
</style>
<body>
<div class="wp">
<div class="box">box</div>
</div>
</body>
使用多種方式實現(xiàn)綠色塊的水平和垂直居中。
一矗愧、居中元素定寬高
- absolute + 負 margin
設(shè)置絕對定位后梯醒,自身的定位是相對于定位為非 static 父級的寬高宽堆。設(shè)置 left 和 top 后,再使 .box 反向偏移自身的寬高一半即可茸习。
.wp {
position: relative;
}
.box {
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
- absolute + calc
與第一種原理相同畜隶,寫法更簡便。
.root {
position: relative;
}
.textBox {
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
}
- absolute + margin auto
依然使用絕對定位号胚,但是設(shè)置各個方向的距離都是 0籽慢,此時配合 margin 為 auto,就實現(xiàn)了在各個方向上都居中了猫胁。
.wp {
position: relative;
}
.box {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
二箱亿、居中元素不定寬高
不定寬高的元素居中在開發(fā)中更為常見,解決的辦法也更多弃秆。
<style>
.wp {
border: 1px solid orange;
width: 300px;
height: 300px;
}
.box {
background: green;
}
</style>
<body>
<div class="wp">
<div class="box">box</div>
</div>
</body>
- absolute + transform
該種方式與定寬高的第一種方式也非常相似届惋,只不過不定寬高時無法反向位移自身的一半髓帽,
這時就可以利用 CSS3 新增的 transform,transform 的 translate 屬性也可以設(shè)置百分比脑豹,這個百分比是相對于自身的寬和高郑藏,在不定寬高時就可以使用。
.wp {
position: relative;
}
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
- lineheight
此種方法是把 box 設(shè)置為 inline-block 行內(nèi)塊元素瘩欺,通過 text-align 可以做到水平居中必盖,同時通過 vertical-align 做到垂直方向上的居中。
.wp {
line-height: 300px;
text-align: center;
font-size: 0px;
}
.box {
font-size: 16px;
display: inline-block;
vertical-align: middle;
line-height: initial;
}
- table
table 在以前經(jīng)常被用來處理頁面布局俱饿,但是隨著前端的發(fā)展歌粥,table 漸漸的退出了大家的視野,不過用來處理居中依然好用拍埠。
<style>
.wp {
text-align: center;
}
.box {
display: inline-block;
}
</style>
<table>
<tbody>
<tr>
<td class="wp">
<div class="box">test</div>
</td>
</tr>
</tbody>
</table>
- css-table
如果感覺 table 方式代碼復(fù)雜失驶、產(chǎn)生冗余,那么就可以使用 css-table械拍,采取 table 布局的特性效果突勇,但是不使用 table 元素装盯。
.wp {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.box {
display: inline-block;
}
- flex
flex 是非常新的布局方式坷虑,實現(xiàn)居中也異常簡單。
.wp {
display: flex;
justify-content: center;
align-items: center;
}
- grid
目前最新的布局方式埂奈,功能強大迄损,但受限于兼容性,沒有得到廣泛的使用账磺。
.wp {
display: grid;
}
.box {
align-self: center;
justify-self: center;
}
完結(jié)
如果遇到居中的需求可以參考以下優(yōu)先級使用
- PC 端有兼容性要求:
寬高固定: absolute + 負 margin
寬高不固定: absolute + transform 和 css-table - PC 端無兼容性要求:flex grid
- 移動端:flex