CSS垂直水平居中 方法集合
阿新 • • 發佈:2018-12-10
在掘金看到一篇有關文章,自己做整理,方便在工作上用到查閱。
需要實現的效果
根據寬度高度是否固定
- absolute + 負margin
- absolute + margin auto
- absolute + calc
根據寬度高度不固定
- absolute + transform
- lineheight
- writing-mode
- table
- css-table
- flex
- grid
# absolute + 負margin
已知有兩個固定寬度高度的div .fa和.sub,要求.sub在.fa中水平居中對齊
<body>
<div class ="fa">
<div class="sub"></div>
</div>
</body>
使用傳統的 position: relative和 position: absolute ,即子絕父相
<style type="text/css">
.fa{
width: 200px;
height: 200px;
border:1px solid;
position: relative;
}
.sub{
width : 100px;
height: 100px;
background-color: skyblue;
position: absolute;
left: 50px;
top: 50px;
}
</style>
使用absolute 和 -margin 效果等同前者
<style type="text/css">
.fa{
width: 200px;
height: 200px;
border:1px solid;
position : relative;
}
.sub{
width: 100px;
height: 100px;
background-color: skyblue;
position: absolute;
left:0;
top:0;
margin-left: 50px;
margin-top: 50px;
}
</style>
這一類寫法效果最好最常用,瀏覽器相容性最佳,但是需要要求元素高度固定。
# absolute + margin auto
同樣作用於高度寬度固定的元素,在子元素 position: absolute 時將”left”, “top”, “right” 以及 “bottom” 設為0,給予margin:auto。
<style type="text/css">
.fa{
width: 200px;
height: 200px;
border:1px solid;
position: relative;
}
.sub{
width: 100px;
height: 100px;
background-color: skyblue;
position: absolute;
left:0;
top:0;
bottom: 0;
right: 0;
margin:auto;
}
</style>
瀏覽器相容性很好,支援所有現代瀏覽器。
# absolute + calc
css3 calc屬性原本是用於在css樣式中做四則運算,在已經高度的情況下可以使元素垂直水平對齊,通過計算得到absolute相對的值。
<!-- 單個div -->
<style type="text/css">
.fa {
position: absolute;
left: calc(50% - 100px);
top: calc(50% - 100px);
width: 200px;
height: 200px;
border: 1px solid red;
}
</style>
<body>
<div class="fa">
</div>
</body>
通過一張圖可以清楚地看出來,整張圖片為瀏覽器視窗物件,通過calc函式計算出當前div的absolute相對位置。
可以結合calc函式實現寬高div中的垂直水平對齊
<!-- div中垂直居中-->
<style type="text/css">
.fa {
position: relative;
width: 200px;
height: 200px;
background-color:pink;
}
.sub {
position: absolute;
width: 100px;
height: 100px;
background-color: skyblue;
top: calc(50% - 50px);
left: calc(50% - 50px);
}
</style>
<body>
<div class="fa">
<div class="sub"></div>
</div>
</body>
效果如圖
因為是CSS3標準,所以相容性還不是非常好,可以參照下圖做對比。
週末接著更新。