塊級元素水平垂直居中的5種技巧

    元素居中分爲水平居中,垂直居中,還有水平垂直居中這三類。其中文本元素和塊元素的居中方式又有略微不同。平時工作中我們最常見的就是塊級元素的水平垂直居中和文字的水平居中了。下面是幾種塊級元素水平垂直居中的方式。

    方式1:margin: auto + 絕對定位 

.wrapper {
    position: relative;
    background: yellow;
    width: 500px;
    height: 300px;
}
.block {
    background: red;
    width: 150px;
    height: 150px;
    margin: auto;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
}

    同理,固定定位也是可以的,主要就是設置子元素的margin,left,top,right,bottom值。
方式2: calc 計算函數 + 相對定位

.wrapper {
    position: relative;
    background: yellow;
    width: 500px;
    height: 300px;
}
.block {
    position: relative;
    background: red;
    width: 150px;
    height: 150px;
    top: calc(50% - 75px);
    left: calc(50% - 75px);
}

     calc函數在css中用於動態計算長度值,運算符前後務必加上空格,否則計算結果不會生效。left: calc(50% -75px) ,可以理解爲,子元素先向右偏移父元素寬度的50%, 然後又向左偏移子元素寬度的一半,也就是75px,這樣一來子元素在水平方向上就居中了。top的距離偏移計算同理。子元素的定位方式也可以是絕對定位,這種居中的技巧本質就是計算好偏移距離。

    方式3:transform

.wrapper
{
    width:500px;
    height:500px;
    background-color:yellow;
}
.block
{
    width: 100px;
    height: 100px;
    background: red;
    transform: translate(200%, 200%)
}

     transform 屬性允許你旋轉,縮放,傾斜或平移給定元素。本質上這種居中技巧是建立在平移量的精準計算之上的。

    方式4:display: flex + 主側軸居中對齊

.wrapper {
    background: yellow;
    width: 500px;
    height: 300px;
    display: flex;
    justify-content: center;
    align-items: center
}
.block {
    background: red;
    width: 150px;
    height: 150px;
}

 方式5:display: flex + margin: auto

.wrapper {
    background: yellow;
    width: 500px;
    height: 300px;
    display: flex;
}
.block {
    background: red;
    width: 150px;
    height: 150px;
    margin: auto;
}

     平時工作中最常用的就是通過flex彈性盒子來做元素的水平垂直居中,因爲這種方式不需要刻意計算各種偏移距離,只要設置主軸和側軸的對齊方式就行了。margin: 0 atuo 常用來設置塊級元素的簡單水平居中。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章