How to perfectly center things in CSS

How to perfectly center things in CSS

To center things perfectly on any and every screen, we’ll be using the powerful flexbox CSS property.

Let’s get started.

  1. Create a new folder called center-things
  2. Navigate into that folder and create an index.html file
  3. Create a styles.css file in the same folder.

Now, Let’s write some basic HTML.

Some notes from the code above.

  1. We have linked our styles.css file to our HTML file.
  2. We are using the Nunito font from google fonts.
  3. We also created a card div and within that div, we have 2 divs. one that holds our text-content named text-content, and one that holds our image(see the link to the image at the end of this article).

Next, head into the styles.css file. Our first task is to use our fonts from google and to change the background-color. We also need to set the minimum-height of the page to 100vh.

If you do not set the minimum-height to 100vh, your content will end up hanging at the top of the page because it doesn’t know that you want to use the entire screen space.

Next, we added some css flex properties to the body.

Justify-content:center aligns our content horizontally along the x-axis while align-items:center aligns our content vertically, along the y-axis.

And that’s it. Your content should now be perfectly centered and look like below.

The rest of the styles below are just to get our card looking great!.

Now our final page would look like below.

The full HTML

Thanks to SLAY for the image used in this tutorial.

Full-stack Engineer. Rails/Node.js/React. I love plantain chips! Reach me at Adebola.dev.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store