Method vertically centered div

Method a: margin: auto Method

Define the upper left is 0, margin: auto, document flow from the center to achieve

//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>

Here Insert Picture Description

Method two: margin method negative

// 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>

Here Insert Picture Description

Method three: using a table-cell (without departing from the document flow)

Set the parent element display: table-cell, and the vertical-align: center, which would allow to achieve div sub-element vertically.

    //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>

Here Insert Picture Description

Method four: the use of flex

The parent element to display: flex ;, and disposed 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>

Here Insert Picture Description

Published 56 original articles · won praise 32 · Views 140,000 +

Guess you like

Origin blog.csdn.net/hry1243916844/article/details/104757777