vertically-center-div-css
CSS Web Development

How to Center Div Vertically with CSS

Vertically centering div can be accomplished by many approaches but the most practical and efficient is using Flex/Grid layout or 2D Transform. Additional consideration is needed if there are more than one div under the same parent

For centering div both horizontally and vertically, read this article instead.

Snippet 1 (Flex/Grid Method)

Add below CSS properties to parent of the div element you want to center.

display: flex;
align-items: center;

Or use below snippet for grid layout

display: grid;  
align-items: center;

Usage Example

HTML

<div class="parentDiv">
  <div class="myDiv"></div>
</div>

CSS

.parentDiv {
 width:300px;
 height: 300px;
 background:lightyellow;
 display: flex;  
 align-items: center;
}
.myDiv {
  width: 50px;
  height: 50px;
  background: red;
}

Live Demo

 

Note
If there are more than 1 elements in the same parent, you’ll probably need to specify flex-direction: row or repeat grid-template-columns

Snippet 2 (2D Transform)

Use CSS 2D transform and absolute position on target element. This will remove the element from normal document flow and independent from other neighbor divs. Add the following CSS properties to target div you want to vertically center.

top: 50%; 
transform: translateY(-50%); 
position: absolute;

Usage Example

HTML

<div class="parentDiv">
  <div class="myDiv"></div>
</div>

CSS

.parentDiv {
  width:300px;
  height: 300px;
  background:lightyellow;
  position: relative;
}
.myDiv {
  width: 50px;
  height: 50px;
  background: red;
  top: 50%;
  transform: translateY(-50%);
  position: absolute;
}
Note
It’s important that the parent element is a positioned element (having position property defined and not static) Above example is setting parent div’s position to relative

Leave a Reply

Your email address will not be published. Required fields are marked *