How to perfectly center things in CSS

Adebola Adeniran
2 min readJun 30, 2020

--

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.

<!DOCTYPE html>
<html lang="en">
<head>
<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" />
<link
href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap"
rel="stylesheet"
/>
</head>
<body>
<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>
</div>
<div>
<img
src="imglink.com"
/>
</div>
</div>
</body>
</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.

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.

--

--

Adebola Adeniran

Chief of Staff at Moni (YC W22) | Developer Advocate Building on Tezos