Search code examples
htmlcssresponsive-designpositionresponsive

How do I properly center this div on mobile and desktop


    <div class="hero">
        <div class="container">
        </div>
    </div>
</body>
    height: 100%;
    background: hsl(212, 45%, 89%);
    
}

.container {
    margin: auto;
    height: 100%;
    background-color: white;
    padding: 1em;
    border-radius: 1em;
    margin: 1.1em;
}
@media only screen and (min-width: 1440px) {
    body {
        height: 100vh;
        display: grid;
        place-items: center;
    }
    .container {
        margin: auto;
        width: 45%;
    }

Mobile version just doesn't vertically center. Desktop ver is centered but there's a scrollbar because of body: 100vh;

Editing the margin doesn't seem to help.


Solution

  • Use min-height: 100vh to vertically center the div. This way it will take the full height but won't make the page scrollable.

    *{
      margin: 0;  /*add this to remove the default body margin*/
    }
    body{
        /*height: 100%;*/ /*<---replace this with min-height: 100vh;*/
        min-height: 100vh;
        display: grid;
        place-items: center;
        background: hsl(212, 45%, 89%);   
    }
    
    .container {
        /*margin: auto;        don't need margin: auto;*/
        height: 50%;
        background-color: white;
        padding: 1em;
        border-radius: 1em;
    }
    @media only screen and (min-width: 1440px) {
        /*body {         <---don't need to specify this anymore
            height: 100vh;
            display: grid;
            place-items: center;
        }*/
        .container {
            width: 45%;
        }
    <div class="container"><div>