国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發(fā) > CSS > 正文

CSS 垂直水平居中的5種最佳解決方案

2024-07-11 08:33:26
字體:
供稿:網(wǎng)友

CSS 居中對齊

代碼中均省略了瀏覽器前綴
以下例子以我的個人的標(biāo)準(zhǔn)排序
當(dāng)然也有更多的居中處理方法 但我覺得只有這5種方法是最完善的解決方案

flex 居中

優(yōu)點:可對未知高度進(jìn)行居中處理


<style>
.wrap{height: 100%;display: flex; justify-content: center; align-items: center;align-content:center;}

.other{background-color: #ccc; width: 400px;height: 400px;} /* 額外的樣式 可去除 */
</style>
<div class="wrap">
<div class="other">
<h2>這是第二層的內(nèi)容 不會居中</h2>
</div>
</div>

position + translate 居中

優(yōu)點: 可對未知高度進(jìn)行居中處理、嵌套層最少


<style>
/* position 可選 absolute|fixed*/
.center{position: absolute;left: 50%;top: 50%; transform: translate(-50%,-50%);}

.other{background-color: #ccc; } /* 額外的樣式 可去除 */
</style>
<div class="center other">
<h2>這一層的內(nèi)容 不會居中</h2>
</div>

table-cell 居中

缺點:1. 居中層需要設(shè)置寬度(.center)。 2.外層多嵌套一層(.cell) 3. 居中層必須設(shè)置寬度(允許 %)


<style>
.wrap{display: table;width: 100%;height: 100%;}
.cell{display: table-cell;vertical-align:middle;}
.center{width: 400px;margin-left:auto;margin-right:auto;}
.other{background-color: #ccc; height: 400px;} /* 額外的樣式 可去除 */
</style>
<div class="wrap">
<div class="cell">
<div class="center other">
<h2>這一層的內(nèi)容 不會居中</h2>
</div>
</div>
</div>

傳統(tǒng)居中 (2種)

缺點:1. margin 值必須為auto。 2. 居中層必須設(shè)置高寬(允許 %) 3. 必須使用 position


<style>
/*
1. left、top、right、bottom 可以任意,但必須相等
2. position 可選 absolute|fixed
*/
.center{position: absolute;left: 10px;top: 10px;right: 10px;bottom: 10px;margin: auto;width: 400px;height: 400px;}
.other{background-color: #ccc; } /* 額外的樣式 可去除 */
</style>
<div class="center other">
<h2>這一層的內(nèi)容 不會居中</h2>
</div>

缺點: 居中層必須設(shè)置固定高寬,并且magin需要通過高寬計算得出。


<style>
.wrap{position: relative;height: 100%;}
.center{position: absolute;left: 50%;top: 50%; width: 400px;height: 300px; margin-left: -200px;margin-top: -150px;}
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 安图县| 成安县| 军事| 宝丰县| 清徐县| 柳林县| 镇坪县| 浏阳市| 汉中市| 洪洞县| 股票| 银川市| 杨浦区| 崇阳县| 南昌县| 拜泉县| 乌拉特后旗| 鸡东县| 顺义区| 德阳市| 遂昌县| 佛坪县| 阿城市| 万安县| 波密县| 鄂伦春自治旗| 邢台市| 黑河市| 清远市| 昭平县| 得荣县| 黄大仙区| 凤城市| 榆社县| 巩义市| 苏州市| 西城区| 老河口市| 嘉禾县| 山阳县| 连州市|