Search code examples
htmlcsscss-grid

Center alignment without the need for height


Seen a few tutorials and doc now. Where its claimed,
all you need to do is the following to both horizontally and vertically align a div.

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

But is not true from what I see. It aligns horizontally but not vertically.

For it to align it vertically, you need to add height.

.grid {
    display: grid;
    place-items: center;
    height: 500px;
}

But this is not being dynamic for it to always stay center for any height. height: 100% doesn't work.
Am I doing something wrong, or the docs / tutorials are incorrect?

Trying this on Edge browser if it matters.

<!DOCTYPE html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <style>

        * {
            padding: 0;
            margin: 0;
        }

        .grid {
            display: grid;
            place-items: center;
        }
    </style>
    <body>
        <article class="grid">
            <div>
                😀
            </div>
        </article>
    </body>
</html>

Doc and tutorial references:

https://developer.mozilla.org/en-US/docs/Web/CSS/place-items

https://www.youtube.com/shorts/njdJeu95p6s

https://youtu.be/qm0IfG1GyZU?t=128


Solution

  • The problem is that you haven't set height to the parent element.

    You can use height: 100%;, but then you also need to set height to the parent element (i.e., <body> in your case).

    See the snippet below.

    <!DOCTYPE html>
    <html>
    
    <head>
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <style>
      * {
        padding: 0;
        margin: 0;
      }
      
      body {
        height: 100vh;
      }
      
      .grid {
        display: grid;
        place-items: center;
        height: 100%;
        border: 5px solid red;
      }
    </style>
    
    <body>
      <article class="grid">
        <div>
          😀
        </div>
      </article>
    </body>
    
    </html>