3 Ways to Center Div in CSS

center div css

Aligning a Div to the center is one of the most required part every developer should know. There are multiple ways to do this and this article show the most common and easy 3 ways to do center div using CSS.

Using the absolute positioning

Most old way to center the div and if you prefer this method you can still use this way. But there are more modern ways to do that in a simple way.

    
        .children{
              width:50px;
              height:50px;
              background:red;
              position:absolute;
              top:50%;
              left:50%;
              transform:translate(-50%,-50%)
            }
            
            <div class="parent">
              <div class="children">
                
              </div>
            </div>
    

Using the Flexbox

Using Flexbox is one of the easiest ways to center the div. You can specify the parent container as flex and justify-content and align-item to center to align item in horizontal and vertical center.

    
        .children{
          width:50px;
          height:50px;
          background:red;
        }
        
        .parent{
          display:flex;
          justify-content:center;
          align-items:center;
          height:200px;
        }
            
            <div class="parent">
              <div class="children">
                
              </div>
            </div>
    

Using the Grid

Most modern approach is use the grid and use the place-items attribute to align item in the center.

    
        .children{
          width:50px;
          height:50px;
          background:red;
        }
        
        .parent{
          display:grid;
          place-items:center;
          height:200px;
        }
            
            <div class="parent">
              <div class="children">
                
              </div>
            </div>
    
Recent Posts