2

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: Desired positioning Current positioning: enter image description here

Abhishek Pandey
  • 13,302
  • 8
  • 38
  • 68
jctwood
  • 131
  • 1
  • 8
  • I have edited my answer with both positioning (the one you currently have and the corrected one) – Ivan Aug 08 '17 at 10:28

3 Answers3

1

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>
Abhishek Pandey
  • 13,302
  • 8
  • 38
  • 68
1

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>
Ivan
  • 34,531
  • 8
  • 55
  • 100
0

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

.container {
  width: 100vw;
  height: 100vh;
  background: lightgray;
}

.h1 {
  font-size: 2em;
}

.welcomeMessage {
  position: absolute;
  text-align: center;
  vertical-align: middle;
  display: inline-block;
  margin: auto;
  width: 60%;
  top: calc(25% - 1em)
}
<div class="container"></div>
<h1 class="welcomeMessage">Welcome</h1>
Gerard
  • 15,418
  • 5
  • 30
  • 52