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

.container {
  width: 300px;
  height: 300px;
  background: red;

  width: 200px;
  height: 200px;
  background: yellow;

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:

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



Buy Me A Coffee

Omar Ghader

Fullstack web engineer and devops. Mobile web specialist