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.

Now, Let’s write some basic HTML.

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>center things</title>
<link href="styles.css" rel="stylesheet" />
<div class="card">
<div class="text-content">
<h2 class="name">Nichole Yembra</h2>
<p class="title">Editor</p>
<p class="company">Slay magazine</p>
<p class="phone"><span>T:</span> +234 798 938 3888</p>

Some notes from the code above.

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.

body {
min-height: 100vh;
background-color: wheat;
font-family: "Nunito", sans-serif;
display: flex;
justify-content: center;
align-items: center;

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.

with flexbox properties applied

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

Now our final page would look like below.

Final look

The full HTML

Thanks to SLAY for the image used in this tutorial.



Growth at Moni(YC W22) |

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