div垂直居中的方法

方法一:margin:auto法

定义上下左右为0,margin:auto,实现脱离文档流的居中

//css
.div1 {
   position: relative;
     width: 200px;
     height: 200px;
     border: 3px solid forestgreen;
     margin-bottom: 20px;
 }

 .div2 {
     position: absolute;
     width: 100px;
     height: 100px;
     background: goldenrod;
     margin: auto;
     top: 0;
     left: 0;
     right: 0;
     bottom: 0;
 }
//html
<div class="div1">
    <div class="div2">
        margin:auto法
    </div>
</div>

在这里插入图片描述

方法二:margin负值法

// css
.div3 {
   position: absolute;
    width: 100px;
    height: 100px;
    background: goldenrod;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;
    /* 或者      */
    /* transform: translateX(-50%);
    transform: translateY(-50%); */
}
  // html
 <div class="div1">
      <div class="div3">
          margin负值法
      </div>
  </div>

在这里插入图片描述

方法三:利用table-cell(未脱离文档流)

设置父元素的display:table-cell,并且vertical-align:center,这样可以让子元素的div实现垂直居中。

    //css
    .div4 {
        position: relative;
        width: 200px;
        height: 200px;
        border: 3px solid forestgreen;
        margin-bottom: 20px;
        display: table-cell;
        vertical-align: middle;
        text-align: center;
    }

    .div5 {
        width: 100px;
        height: 100px;
        background: goldenrod;
    }
	// html
  <div class="div4">
      <div class="div5">
           table-cell
       </div>
   </div>

在这里插入图片描述

方法四:利用flex

将父元素设置为display: flex;,并且设置align-items: center;justify-content: center;

// css
 .div6 {
    position: relative;
     width: 200px;
     height: 200px;
     border: 3px solid forestgreen;
     display: -webkit-flex;
     display: flex;
     -webkit-align-items: center;
     align-items: center;
     -webkit-justify-content: center;
     justify-content: center;
 }

 .div7 {
     width: 100px;
     height: 100px;
     background: goldenrod;
 }
// html
 <div class="div6">
    <div class="div7">
         利用flex
     </div>
 </div>

在这里插入图片描述

发布了56 篇原创文章 · 获赞 32 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/hry1243916844/article/details/104757777