div水平垂直居中的六種方法

在平時,咱們常常會碰到讓一個div框針對某個模塊上下左右都居中(水平垂直居中),其實針對這種狀況,咱們有多種方法實現。css

方法一:html

  絕對定位方法:不肯定當前div的寬度和高度,採用 transform: translate(-50%,-50%); 當前div的父級添加相對定位(position: relative;web

  圖片展現:函數

  

  代碼以下:佈局

div{
    background:red;
    position: absolute;
    left:50%;
    top:50%;
    transform: translate(-50%, -50%);
} 

 

方法二:flex

  絕對定位方法:肯定了當前div的寬度,margin值爲當前div寬度一半的負值spa

  圖片展現: 如方法一的圖片展現orm

  代碼以下:htm

div{
    width:600px;
    height: 600px;
    background:red;
    position: absolute;
    left:50%;
    top:50%;
    margin-left:-300px;
    margin-top:-300px;
} 

  

方法三:blog

  絕對定位方法:絕對定位下top left right bottom 都設置0

  圖片展現: 如方法一的圖片展現

  代碼以下:

<!--html-->
<div class="child">我是子級</div>
/**css**/
div.child{
    width: 600px;
    height: 600px;
    background: red;
    position:absolute;
    left:0;
    top: 0;
    bottom: 0;
    right: 0;
    margin: auto;
}

  

方法四:

  flex佈局方法:當前div的父級添加flex css樣式

      展現圖以下:

  

  代碼以下:

<!--html-->
<div class="box">
    <div class="child">child</div>
</div>
/**css**/
.box{
    height:800px;
    -webkit-display:flex;
    display:flex;
    -webkit-align-items:center;
    align-items:center;
    -webkit-justify-content:center;
    justify-content:center;
    border:1px solid #ccc;
}
div.child{
    width:600px;
    height:600px;
    background-color:red;
}

  

方法五:

  table-cell實現水平垂直居中: table-cell middle center組合使用

      展現圖以下:

    

      代碼以下:

<!--html-->
<div class="table-cell">
    <p>我愛你</p>
</div>
/**css**/
.table-cell {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    width: 240px;
    height: 180px;
    border:1px solid #666;
}

  

方法六:

  絕對定位:calc() 函數動態計算實現水平垂直居中

  展現圖以下:

  代碼以下:

<!--html-->
<div class="calc">
    <div class="child">calc</div>
</div>
/**css**/
.calc{
  position: relative;  border: 1px solid #ccc;  width: 400px;  height: 160px;
}
.calc .child{
  position: absolute;  width: 200px;  height: 50px;
  left:-webkit-calc((400px - 200px)/2);
  top:-webkit-calc((160px - 50px)/2);
  left:-moz-calc((400px - 200px)/2);
  top:-moz-calc((160px - 50px)/2);
  left:calc((400px - 200px)/2);
  top:calc((160px - 50px)/2);
}  
相關文章
相關標籤/搜索