Div not obeying ‘top’ or ‘height’ styles
I have a
.panel div that I have created, with some contents in it. I want it to be centered both vertically and horizontally. Horizontal cenetering I have accomplished using
margin:auto;, but I cant seem to get the vertical centering to work.
As per this tutorial, which I have used successfully many times in the past, I have styled my
The position is set to relative, and it is transformed upwards by 50% of it’s size, but the top stays at 0%, and thus, the panel is half offscreen. As well, the panel’s height is set to 95%, but it is not obeying that either. This is not as important—in the end I want the height to be auto—but I noticed it happening, and figured it might be caused by the same issue that’s preventing the top from being set properly. Any idea what is causing this?
It’s because you are using percentage based units. If you want the element centered relative to the window, then the
body needs to have a height larger than its contents (at the moment, the
height of the
body element is defined based on the
In this case, you could just give it a height of the viewport:
You could also absolutely position the element instead.
Alternatively, another way to center the element horizontally/vertically would be to add
top: 0; right: 0; bottom: 0; left: 0;, then since a
width are given,
margin: auto will effectively center the element horizontally/vertically.
But since the
height are specified using percentage based units, you could actually use just center the element using