How to center an element using CSS

In some cases, it is always easy to use CSS to center elements, in other cases it is difficult. This is how to be CSS-centric and a complete list of modern CSS techniques

If you need to center horizontally or vertically, centering an element in CSS is a very different task.

In this article, I will explain the most common scenarios and how to solve them. If a new solution is providedFlexible boxI ignored the old technology because we need to move on, and Flexbox has been supported by browsers (including IE10) for many years.

Horizontally centered

text

The text is very simple, you can usetext-alignAttribute is set tocenter:

p {
  text-align: center;
}

Building Blocks

The modern way to center non-text content is to use Flexbox:

#mysection {
  display: flex;
  justify-content: center;
}

Any element inside#mysectionCenter the level.

Center horizontally


If you don't want to use Flexbox, this is another way.

You can center all non-text content by applying automatic margins on the left and right and setting the width of the element:

section {
  margin: 0 auto;
  width: 50%;
}

the abovemargin: 0 auto;Is shorthand for the following:

section {
  margin-top: 0;
  margin-bottom: 0;
  margin-left: auto;
  margin-right: auto;
}

Remember to set the project todisplay: blockIf it is an inline element.

Vertically centered

Traditionally, this has been a daunting task. Now, Flexbox provides us with a great way to accomplish this in the easiest way:

#mysection {
  display: flex;
  align-items: center;
}

Any element inside#mysectionWill be centered vertically.

Center vertically

Vertically centered and horizontally centered

You can combine the vertical and horizontal centering techniques of Flexbox to completely center the elements on the page.

#mysection {
  display: flex;
  align-items: center;
  justify-content: center;
}

Center both vertically and horizontally

can useCSS grid:

body {
  display: grid;
  place-items: center;
  height: 100vh;
}

Download mine for freeCSS Manual


More CSS tutorials: