css 水平垂直居中的方法總結

在項目中常常會遇到設置元素水平垂直居中的需求。並且具體的場景也不一樣,因此將我的總結的方法作個彙總,但願對瀏覽者有用。
如下所舉的例子都以一個html爲準,這裏規定好一些公用樣式。html

body {
    background-color: #efefef; 
}
main {
    background-color: #fff;
    padding: 10px;
    margin:10px 0px;
}
main div {
    background-color: #aaf;
}

水平居中

1 相對塊級父元素,可將子級設置成行內或者行內塊元素,父元素設置text-align屬性

舉例以下:flex

.parent1 {
    text-align:center;
}
.child1 {
    display:inline|inline-block;
}

2 若父子都爲塊級元素,則給子元素寬度值以後,將margin:auto

<main class="parent2">
    <div class="child2">我是孩子2,我要水平居中</div>
</main>
.child2 {
    width:60%;
    margin:auto;
}

3 若是是多個子元素水平居中,則有兩種方法

3.1 將子級設置成行內或者行內塊元素,父元素設置text-align屬性
3.2 將父元素設置display:flex
<main class="parent4">
    <div class="child4">我是孩子4,我要水平居中</div>
    <div class="child4">我是孩子4,我要水平居中</div>
    <div class="child4">我是孩子4,我要水平居中</div>
</main>

.parent4 {
    display: flex;
    justify-content: center;
}
  .child4 {
    margin:10px;
}

垂直居中

1 除了設置固定的padding值使其看起來垂直居中以外,還可用line-height

將line-height和height的值設置爲相同值,code

<main class="parent5">
    <div class="child5">我是孩子5,我要垂直居中</div>
</main>
.child5 {
    height:50px;
    line-height: 50px;
}

2 若是是多行的,能夠像table那樣,按照table cell 模式顯示,配合vertical-align

<main class="parent6">
    <div class="child6">我是孩子6,我要垂直居中</div>
    <div class="child6">我是孩子6,我要垂直居中</div>
    <div class="child6">我是孩子6,我要垂直居中</div>
</main>
.parent6 {
    display: table;
}
.child6 {
    display: table-cell;
    border:2px solid #000;
    vertical-align: middle;
}

3 經過絕對定位

<main class="parent7">
    <div class="child7">我是孩子7,我要垂直居中</div>
</main>
/*若是知道子元素寬高*/
.parent7 {
    position: relative;
    height: 100px;
}
.child7 {
    position: absolute;
    top:50%;
    height:60px;
    margin-top:-30px;
}
/*若是不知道子元素寬高*/
.parent7 {
    position: relative;
    height: 100px;
}
.child7 {
    position: absolute;
    top:50%;
    transform: translateY(-50%);
}

4 使用flex

<main class="parent8">
    <div class="child8">我是孩子8,我要垂直居中</div>
</main>
.parent8 {
    height: 200px;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

水平和垂直都居中

1 使用絕對定位

<main class="parent9">
    <div class="child9">我是孩子9,我要水平垂直居中</div>
</main>
 /*若是不知道子元素寬高*/
.parent9 {
    position: relative;
    height: 150px;
}
.child9 {
    position: absolute;
    top:50%;
    left:50%;
    transform: translate(-50%,-50%);
}
/*若是知道子元素寬高*/
.parent9 {
    position: relative;
    height: 150px;
}
.child9 {
    position: absolute;
    top:50%;
    left:50%;
    height:60px;
    width:100px;
    margin-left:-50px;
    margin-top:-30px;
}

2 使用flex

.parent10 {
    height: 200px;
    display: flex;
    flex-direction: column;
    justify-content: center;
}
.child10 {
    margin: auto;
}

3 除此以外,還能夠將上述的水平和垂直分別居中的方法,嘗試着搭配。固然,應該還有其它方法,待發現。

上述結果輸出截圖


相關文章
相關標籤/搜索