Categories
CSS Web

Vertically & Horizontally Centering an Element with CSS in 2020

Centering an element vertically and horizontally with CSS several years ago was nearly impossible. The process often involved either CSS negative margins or table layouts… all sorts of impractical rubbish.

Then CSS flexbox happened. Flexbox made centering and moving elements around the screen fun for the first time in the history of CSS. In fact, with flexbox, it takes only 3 CSS properties to position an element in the true-center of a given context (true-center being both the vertical and horizontal center).

<style>
    body {
        height: 100vh;
        margin: 0;
    }

    .block-center {
        display: flex;
        justify-content: center;
        align-items: center;
    }
</style>

<body class="block-center">
    <main>
        <h1>Hello</h1>
    </main>
</body>

However, we live in the year is 2020. CSS gird is widely supported and Internet Explorer is finally going away forever. We can confidently use CSS Grid’s place-items property to position elements in true-center today.

.block-center {
    display: grid;
    place-items: center center;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.