Positioning a div relative to its vertical centre

This question already has an answer here:

  • Element will not stay centered, especially when re-sizing screen

    2 answers

I have a welcome message which needs its centre to be positioned at 25% from the top of the window. Because it could be any number of lines long it needs to be positioned using its vertical centre. Here is what I have currently.

.welcomeMessage {
  position: absolute;
  text-align: center;
  vertical-align: middle;
  display: inline-block;
  margin: auto;
  width: 60%;
  top: 25%;
}

I have tried using display: inline-block and display: flex with vertical-align: middle but neither position the div relative to its vertical centre. Any help would be greatly appreciated!

Desired positioning:

Current positioning:



In the snippet bellow I have two elements, both set to position:absolute with top: 25% and left: 50% .

  • .element as transform: translate(-50%, -50%); that allows him to center vertically and horizontally “exactly” at 25% of the page dimensions (height, width). Because unlike top and left, the transform property is based on the size of the target element. So the percentage you set refers to the size of the bounding box of the target.
  • .other in the other hand doesn’t have a transform rule so it’s not positioned like you wanted it to be, its top border sits at 25%
.element,
.other {
  position: absolute;
  text-align: center;
  top: 25%;
  left: 50%;
}

.element {
  transform: translate(-50%, -50%);
  color: green;
}

.other {
  color: red;
}
html,body{
  height:100%;
  margin:0;
  padding:0;
}
<div class="element">I'm at 25% middle</div>
<div class="other">I'm not at 25% middle</div>

Use transform:translate(-50%);

margin: auto; does not work with inline-block elements, so you need to add left:50% to make it horizontally center.

html,body{
  height:100%;
  margin:0;
  padding:0;
}

.welcomeMessage {
  position: absolute;
  text-align: center;
  vertical-align: middle;
  display: inline-block;
  left:50%;
  width: 60%;
  top: 25%;
  transform:translate(-50%);
}
<div class="welcomeMessage">Welcome Message</div>

This should probably work. I defined the size for h1 as 2em and calculate the top position, decreasing 25% with half the font size.