简体   繁体   中英

How to center a div from top to bottom?

I just want the div to be in the center of the page, equal spacing from top to bottom and I need to use percents because the div content varies. I tried bottom:50% but this does not work.

Thanks for the answers! Mine's a little different and it is my mistake for not adding this, visit my blog to view the issue.

Hey everyone, thanks for using your time to answer such a stupid question, but I found that the easiest way is to just use padding:

padding-top:X%;
padding-bottom:X%;

Then just mess with it to see what your result is. If you have anything better PLEASE DO SHARE because this is obviously probablly not the most reliable.

Your answer of using percentages in padding doesn't work in all situations. This is because padding percentages are based on the width of the element you are adding padding to and not the height of it. Plus, it's not at all based on the container you want the element centered within. So if you were to decrease the width of your browser window, your DIV would move to a location that is no longer centered within the browser window because the width of the DIV has changed, causing the percentage value of your padding to change as well.

To truly center your DIV no matter the browser window dimensions, the code below should help tremendously:

  .div {
     position: fixed;
     top: 50%;
     left: 50%;
     transform: translate(-50%, -50%);
  }

vertical-align:center垂直对齐,然后text-align:center水平text-align:center

#mydiv {
  position:absolute;
  top:20%; bottom:20%
}

See also Understanding Vertical Align .

#div{
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
height:100px;
width:100px;
}

this code aligns either bottom to top,or left to right but you have to set width and height.
Or use this:

#div{
display:flex;
align-items:center;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM