Div not obeying ‘top’ or ‘height’ styles

Fiddle

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 .panel with

.panel {
  position:relative;
  top:50%;
  transform: translateY(-50%);
}

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?


solution

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 .panel element).

In this case, you could just give it a height of the viewport:

Updated Example

body {
height: 100vh;
}

You could also absolutely position the element instead.

Updated Example

.panel {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

Alternatively, another way to center the element horizontally/vertically would be to add top: 0; right: 0; bottom: 0; left: 0;, then since a height/width are given, margin: auto will effectively center the element horizontally/vertically.

Updated Example

.panel {
  position: absolute;
  width: 95%;
  height: 95%;
  margin: auto;
  top: 0; right: 0;
  bottom: 0; left: 0;
}

But since the width/height are specified using percentage based units, you could actually use just center the element using top: 2.5%/left: 2.5%.

Updated Example

.panel {
  position: absolute;
  width: 95%;
  height: 95%;
  left: 2.5%;
  top: 2.5%;
}