DEV Community

Cory Rylan
Cory Rylan

Posted on • Originally published at coryrylan.com

How to Center in CSS with Flexbox

There are many ways to center things in CSS but one of the easiest ways is to use CSS Flexbox. CSS Flexbox is a layout model that helps align one directional items. This short post we will take a look at how to center items not only horizontally but also vertically.

First we will start simple with wanting to center a single item in a parent container.

<section>
  <div>1</div>
</section>
Enter fullscreen mode Exit fullscreen mode
section {
  width: 200px;
  border: 1px solid #2d2d2d;
}

div {
  color: #fff;
  background: #2d2d2d;
  padding: 12px;
  display: inline-block;
}
Enter fullscreen mode Exit fullscreen mode

Inline block item to be centered with CSS Flexbox

To center the inner div element we will make the parent a flex container.

section {
  width: 200px;
  border: 1px solid #2d2d2d;
  display: flex;
  justify-content: center;
}
Enter fullscreen mode Exit fullscreen mode

By adding the display: flex; property we make the section element a flex container allowing us to adjust the layout of the div which is now a flex item. To center out item horizontally we use the justify-content: center;. The justify-content property allows us to position items along the main axis of the flex container. This the main axis can change dependent on the flex-direction.

Inline block item centered with CSS Flexbox

The justify-content property also has the start, end and stretch that can position items along the main axis.

Centering Vertically

Now we have our element centered horizontally we can center our element vertically. Let's increase our parent container to be 200px high.

Inline block item to be vertically centered with CSS Flexbox

Not quite what we expect. By default flex items will fill vertical space of their parent element. To vertically center our div we can add a single CSS property.

section {
  width: 200px;
  border: 1px solid #2d2d2d;
  display: flex;
  justify-content: center;
  align-items: center;
}
Enter fullscreen mode Exit fullscreen mode

By using align-items: center we can vertically center all flex items to the parent container along the cross axis of the flex container.

Inline block item to be vertically centered with CSS Flexbox

The nice aspect of flexbox is the styles apply to all children of our flex container. If we add two more elements they all stay centered within the parent select.

<section>
  <div>1</div>
  <div>2</div>
  <div>3</div>
</section>
Enter fullscreen mode Exit fullscreen mode

Inline block item horizontally centered with CSS Flexbox

Check out the full working demo and center all the things!

Top comments (0)