/ #html #css 

How to center a element inside div with css

Centering elements inside div is a common problem in web development. In this post I will explain a very easy solution for this that works always.

Before centering

Let’s say we have those 2 containers.

<div class="container">
  <div class="center-element"></div>
</div>

<style>
  .container {
    width: 300px;
    height: 300px;
    background: red;
  }

  .center-element {
    width: 200px;
    height: 200px;
    background: yellow;
  }
</style>

Centering the element

The easiest way is to use the flex display that handles the centering in very good way.

We will modify our code as following:

<style>
  .container {
    ...
    display: flex;
    justify-content: center; /* center horizontal */
    align-items: center; /* center vertical */
    ...
  }
</style>

Sources