DEV Community

Cover image for Beginner CSS: Center Content with Flexbox
Cory Tanner
Cory Tanner

Posted on • Updated on

Beginner CSS: Center Content with Flexbox

The firehose of web development information out there can overwhelm even the smartest of people. If you're a beginner web developer, it can feel like there is no way to learn everything. But, try and keep things in perspective! The best steps are to start simple and continuously build on that foundational knowledge.

So let's start simple! Centering content with CSS Flexbox.

CSS properties to learn

display: flex; - Flexbox overview
justify-content: center; - Overview
align-items: center; - Overview

HTML/CSS Example

<section class="hero">
  <h1 class="hero__heading">Hi</h1>
</section>
Enter fullscreen mode Exit fullscreen mode
.hero {
  display: flex;
  justify-content: center;
  align-items: center;
}

.hero__heading {
  display: inline-block;
}
Enter fullscreen mode Exit fullscreen mode

The important aspects from the code above that you should note is that we are using the parent element <section class="hero"> to center the content within it. Honestly it's that simple.

justify-content

justify-content: center; tells all child elements to align themselves center on the main axis.

align-items

align-items: center; tells all child elements to align themselves center on the cross axis.

Have fun using this in your applications and I highly encourage you to master Flexbox and CSS Grid. These two CSS skills will be the foundation of app layout for many years to come.

Resources

  • Codepen Example:
  • YouTube:

Top comments (0)