How do I center a div vertically and horizontally

Code snippet

// HTML
<div class="parent">
  <div class="child"></div>
</div>
Absolute positioning
.parent{ position:relative; } // The first. Child {position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); Child {position:absolute;} position:absolute; width:100px; height:100px; top:50%; left:50%; margin-left:-50px; margin-top:-50px; Child {position:absolute; width:100px; height:100px; left:0; top:0; bottom:0; right:0; margin:auto; }}.child{position: absolute; width: 100px; height: 100px; left: 50%; top: 50%; background: yellow; transform: translate(-50px, -50px); }
Flex layout
.parent { width: 500px; height: 500px; background: pink; display: flex; align-items: center; justify-content: center; } // The child element can be fixed. Parent.child {width: 100px; height: 100px; background: yellow; } // child element does not set width. Parent.child {background: yellow; }
table-cell
.parent { width: 500px; height: 500px; display: table-cell; text-align: center; vertical-align: middle; background: pink; } .parent .child { display: inline-table; Display: inline-block; /* / display: inline-block; display: inline; */ width: 100px; height: 100px; background: yellow; }
Grid
.parent {
  width: 500px;
  height: 500px;
  display: grid;
  background: pink;
}
.parent .child {
  align-self: center;
  justify-self: center;
  width: 100px;
  height: 100px;
  background: yellow;
}

Demo

conclusion

There are two ways to center a div vertically and horizontally. The first way is if the element is not fixed in width and height. There are three ways

  1. Use absolute positioning plus transform offset
  2. Using the Flex layout, set align-items:center; justify-content:center;
  3. Using the grid layout, set align-self:center; justify-self:center;

If the element has a fixed width and height, you can use:

  1. Absolute positioning + Transform offset
  2. Absolute positioning + negative margin value
  3. Absolute positioning +margin:auto
  4. Three ways of not fixing the width and height
reference

The front-end advanced