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%);
}
#mydiv {
position:absolute;
top:20%; bottom:20%
}
See also Understanding Vertical Align.
vertical-align:center
for vertically aligning
then text-align:center
for horizontal
#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;
}
精彩评论