THE PERFECT HACK TO CENTER a DIV?
Here is how it's done...

THE PERFECT HACK TO CENTER a DIV? Here is how it's done...

Β·

1 min read

Do you always have to Google how to center a div, or is it just me? I certainly hope I'm not the only one. 🀞

There are many tricks to use when centering a DIV, but in this article, we would use FLEXBOX to place our div at the center of our page.

1. Create your div container in the body of the HTML file and give it a class or ID, whichever is your preference.

<body>
    <div class="container">
      <p>
        My name is DIV and <br />
        Rachel centered me πŸ’ƒπŸŽ‰
      </p>
    </div>
   </body>

2. Style the div with a width, height and border to make it visible.

 .container {
   width: 300px;
   height: 300px;
   border: 4px solid black;
   background-color: aqua;
 }

3. In your CSS file, target the parent element of the div. In our example, it will be the body. Then give it the following style using FLEXBOX

However, for the div to be properly centered, you should give a height of 100vh.

 body {
   height: 100vh;
   display: flex;
   justify-content: center;
   align-items: center;
   background-color: bisque;
 }

Take note that this is not the only way to center a Div, but this works for me and I thought to share it with you.

Let me know in the comment if it works for you too. Cheers and Happy codingπŸ₯‚

Β