-1

I am looking for a way to position the <h1> tag below vertically central inside the absolutely positioned container div. I am aware of display: table and display: table-cell, however this does not play well with absolute positioning.

<div class="position--relative">
    <div class="position--absolute">
        <h1>POSITION THIS TEXT CENTRALLY INSIDE THE CONTAINER</h1>
    </div>
</div>

Is there a way I can position this text centrally without using px units? This is because it will need to stay central on various viewports.

crmpicco
  • 16,605
  • 26
  • 134
  • 210

4 Answers4

1

What is wrong with display: table and display: table-cell

Try this:

* {
  margin: 0;
  padding: 0;
}
html,
body {
  width: 100%;
  height: 100%;
}
.position--relative {
  position: relative;
  width: 100%;
  height: 100%;
}
.position--absolute {
  position: absolute;
  width: 100%;
  height: 100%;
}
.table {
  display: table;
  width: 100%;
  height: 100%;
}
.cell {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}
<div class="position--relative">
  <div class="position--absolute">
    <div class='table'>
      <div class='cell'>
        <h1>POSITION THIS TEXT CENTRALLY INSIDE THE CONTAINER</h1>
      </div>
    </div>
  </div>
</div>

Fiddle here

Rayon
  • 36,219
  • 4
  • 49
  • 76
0

Move the element 50 % from top and than use a transform to move it up half of its size:

h1 {
  margin: 0;
  position: relative;
  transform: translateY(-50%);
  top: 50%;
}

Demo: JSFiddle

KittMedia
  • 7,368
  • 13
  • 34
  • 38
0

Using transform you can easily achieve this both horizontally and vertically.

 .position--absolute
 {
   position:absolute;  
   top:50%;
   left:50%;
   transform: translate(-50%,-50%);
}

DEMO

Nice article available with so many scenario's. https://css-tricks.com/centering-css-complete-guide/

Suresh Ponnukalai
  • 13,820
  • 5
  • 34
  • 54
0

Here you go if you don't want to use table and table-cell :) top and left set to 50%. The translate value for transform is based off the size of the element, so that will center nicely.

Read more about these tricks in - https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/ Snippet

.position--relative {
  position: relative;
  height: 250px;
  background: #333;
}
.position--absolute {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  text-align: center;
}
h1 {
  color: #fff;
}
<div class="position--relative">
  <div class="position--absolute">
    <h1>POSITION THIS TEXT CENTRALLY INSIDE THE CONTAINER</h1>
  </div>
</div>
Jinu Kurian
  • 9,128
  • 3
  • 27
  • 35