浮層水平垂直居中方法

(一)利用絕對定位與transform

         <div class="parent">

      <div class="children"></div>

    </div>

  將父元素定位,子元素如下

  .children{
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform:translate(-50%,-50%);
    background: black;
  }

 

(二)利用flexbox

 

  .parent{

    justify-content:center;
    align-items:center;
    display: -webkit-flex;

  }

 

(三)當子元素的寬高固定,父元素內含有除居中元素外其它元素(空標籤也行)或者父元素的高度不爲0時

  將父元素定位,子元素絕對定位,利用margin負值爲子元素寬高的一半來實現。

  代碼如下:

    <div class="parent">

      <div class="children"></div>

      <span></span>
    </div>

    .parent{

             height:400px;//有除對定位元素外其它元素時可不設,若沒有則需要
               position: relative;
               background: red;
            }
          .children{
               width: 200px;
               height: 200px;

               margin: -100px 0 0 -100px;
               background: black;
               position: absolute;
               top: 50%;
               left:50%;

          }

  

(四)利用table

      table的td默認內容垂直居中。只要再設置內容水平居中即可
 

(五)display:table-cell

      CSS中有一個用於豎直居中的屬性vertical-align,但只有 當父元素爲td或者th時,這個vertical-align屬性纔會生效,對於其他塊級元素,例如 div、p等,默認情況下是不支持vertical-align屬性的,可以設置塊級元素的display類型爲table-cell,激活vertical-align屬性,但display:table-cell存在兼容性問題,所以這種方法沒辦法跨瀏覽器兼容。
  

  <div class="parent">
    <div class="child">哈哈</div>
  </div>

  .parent{
    width: 400px;
    height: 100px;
    background: black;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
  }

  .child{
    background: red;
    display: inline-block;
  }

 

display:table-cell的兼容情況
 

(六)利用定位與margin:auto

   <div class="parent">
    <div class="child">哈哈</div>
  </div>
       .parent{
               width: 600px;
               height: 400px;
               background: red;
               position: relative;
          }
          .children{
               width: 200px;
               height: 200px;
               position: absolute;
               top: 0;
               left: 0;
               bottom: 0;
               right: 0;
               margin: auto;

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