How To Center A <div>

04 Aug 2024

a graphic

In the past this was a big question. Now when you're asking this question in r/webdev you are considered a Troll. If you don't know where's the problem: Congratulations. You are young! Nowadays there is not much to say about it. Some memes remain and that warm feeling you get when you learn that something is solved by flexbox or grid.

Centering with flexbox works with justify-content. This aligns the contents on the main axis (default: horizontal). With align-items we control the alignment of items on the cross axis. It's so easy that I didn't use it in this page's layout :)

<style>
  section {
    display: flex;
    justify-content: center;
    align-items: center;

    height: 200px;
    outline: 2px solid palegreen;
  }

  div {
    background-color: aqua;
    padding: 3px;
  }
</style>
<section>
  <div>center w flexbox</div>
</section>

Note: The inner div element could also be a simple TextNode. It would still work!

With grid we need align-content:center and justify-content:center. The shorthand that sets both values is place-content:center

<style>
    section {
        display: grid;
        place-content: center;

        height: 200px;
        outline: 2px solid palegreen;
    }

    div {
        background-color: aqua;
        padding: 3px;
    }
</style>
<section>
    <div>center w grid</div>
</section>

Of course there are other, older ways, like using margin: 0 auto for at least horizontal centering. and there is transform:translateX(-50%).

Let's have a trial at the auto-margin trick. This kinda works. You need to constraint the width of the centered element. Instead of a relative or fixed width, you could also try something like max-width:fit-content.

<style>
    section {
        height: 200px;
        outline: 2px solid palegreen;
    }

    div {
        margin: 0 auto;
        text-align: center;
        width: 50%;
        background-color: aqua;
        padding: 3px;
    }
</style>
<section>
    <div>horiz. center w margins</div>
</section>

If you are really interested in life in the stone age -- they used to do layouts completely based on tables. Just open your inbox and have a look at the source code of one of your fancy html emails.