Home > Net >  How do I properly center this div on mobile and desktop
How do I properly center this div on mobile and desktop

Time:11-17

    <div >
        <div >
        </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.

CodePudding user response:

You can use flex-box to center anything, apply the following CSS to it.

To show it aligns the item to the center, I made a red box.

Now you can add more CSS to it.

.hero{
  display: flex;
  align-items: center;
  justify-content: center;
}
.container{
  background : red;
  width: 100px;
  height :100px;
}
<div >
        <div ></div>
 </div>

CodePudding user response:

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 ><div>

  • Related