CSS || 元素垂直居中筆記

CSS種元素垂直居中

根據不一樣狀況,使用的垂直居中方式各異:針對塊級元素與行級元素的垂直居中不一樣。css

1 行級元素

1.1 行內包含特殊元素

  • 若是行內包含特殊元素:圖片、input輸入框、inline-block元素或者粗體佈局

  • 使用verticle-align: middle;設置對齊方式便可垂直居中。text-bottom/text-top 爲下對齊/上對齊post

  • 兼容性很好:IE4flex

1.2 設置line-height

  • 設置line-heightheight值相等,能夠實現行級元素或者純文本的塊級元素的垂直居中code

  • 兼容性好IE4orm

2 塊級元素

2.1 flexalign-items

  • 設置容器元素display: flex; align-items: center;便可,其內的子元素在容器中垂直居中繼承

  • 缺點: 使用flex佈局,而且使用CSS3的align-items屬性,兼容性較差:IE11圖片

2.2 flexalign-self

  • 設置容器元素display: flex; ,子元素設置align-self: center;input

  • align-self屬性容許單個項目有與其餘項目不同的對齊方式,可覆蓋align-items屬性。默認值爲auto,表示繼承父元素的align-items屬性,若是沒有父元素,則等同於stretchit

  • 一樣兼容性較差:IE11

2.3 絕對定位

  • 父元素設置相對定位position: relative;

  • 子元素設置絕對定位postion: absolute; top: 0; left:0; bottom: 0; right: 0; margin: auto;

  • 關鍵在於設置top: 0; left:0; bottom: 0; right: 0; margin: auto表示水平、垂直4個方向的margin值都經過計算獲取

  • 兼容性IE7

    <div class="wrap">
    <div class="child"></div>
    </div>
    
    <style type="text/css">
    * {margin: 0; padding: 0;}
    .wrap {position: relative; 100vw; height: 100vh;}  /* 注意清除margin和padding,不然100vh不對*/
    .child {
      position: absolute;
      top: 0;
      bottom: 0;
      right: 0;
      left: 0;
      margin: auto;
      width: 200px;
      height: 100px;
      background: lightgreen;
    }

2.4 display: table-cell

  • 表格元素能夠設置verticle-align: middle;實現垂直居中

  • 爲容器添加display: table-cell; verticle-align: middle;

  • 缺點是不能設置百分比寬度,能夠設置固定像素值

  • 兼容向IE8

2.5 絕對定位

  • 利用父元素相對定位,子元素絕對定位,而且處置、水平方向個偏移50%

  • 子元素利用負值margin偏移自身寬度、長度的一半

  • 缺點是須要固定子元素的寬高

  • 兼容性IE7

2.6 絕對定位使用translate()屬性

  • position: absolute; top: 50%; left: 50%;中,50%是相對容器的寬度

  • transform: translate(-50%, 50%)是相對於元素自身的寬度,無需再用負的margin

    父元素設置{ position: relative; }
    子元素設置{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, 50%) }
相關文章
相關標籤/搜索