Centering vertically using (only) CSS

Centering vertically using (only) CSS

Overview

Have you ever found yourself sweating bullets over a seemingly simple CSS task like centering elements vertically? Fear not! Today, I’m sharing a nifty little code snippet that’s been my go-to solution.

2024 update!

Alright, it’s 2024, and it’s time to update this post… Here’s a modern tweak for vertically centering a div using flexbox, which is both efficient and widely supported. This method ensures your content is perfectly centered, both vertically and horizontally, within its container. Just apply the following CSS properties to your container:

display: flex;
align-items: center;
justify-content: center;

This approach provides a cleaner, more robust solution compared to traditional methods, adapting seamlessly across different screen sizes and content changes. Happy coding!

Here’s a snippet to showcase this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flexbox Centering Demo</title>
    <style>
        .centered-container {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
            background-color: salmon;
        }
    </style>
</head>
<body>
    <div class="centered-container">
        <p>Hello, world! I'm perfectly centered.</p>
    </div>
</body>
</html>

In this example, I’m adding a height to the container, otherwise it will be the same height as the content.

Hope that helps! :)

Original post (2017)

You wrote on your resume that you have advanced knowledge on CSS. A recruiter calls you and asks one question: You said you have advanced knowledge on CSS… Prove it! How do you center elements vertically?

All hell breaks lose and you start asking yourself what have you done with your life…

Well, not anymore, the following code may help you:

position: relative; 
top: 50%; 
transform: translateY(-50%);

That snippet may need a few tweeks, but it has worked for me so far.

Good luck!

Image without description

Image without description

Translations: