DEV Community

JT Dev for JetThoughts LLC

Posted on • Updated on

How to vertically center an element without Flex

How vertically center with Flex you can view Vertical align with a full screen across Tailwind CSS

<div class="outer">
  <div class="inner">Centered</div>
</div>
Enter fullscreen mode Exit fullscreen mode

Transform Translate

It’s possible to center it by nudging it up half of it’s height after bumping it down halfway:

.outer {
  position: relative;
  height: 100vh;
}
.inner {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
Enter fullscreen mode Exit fullscreen mode

Display: Table-Cell

Outer element to be displayed as a table and the inner element to be displayed as a table-cell which can then be vertically centered.

.outer {
  display: table;
  height: 100vh;
}
.inner {
  display: table-cell;
  vertical-align: middle;
}
Enter fullscreen mode Exit fullscreen mode

Fixed Height

Set margin-top: -yy where yy is half the height of the inner container to offset the item up.

.outer {
  position: relative;
  height: 100vh;
}
.inner {
  position: absolute;
  height: 100px;
  margin-top: -50px;
  top: 50%;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
rollergui profile image
Guilherme

good tips! css is too hard for me :(
anyway, is there a reason not to use flex? is the compatibility not good enough yet? thanks :)

Collapse
 
jetthoughts_61 profile image
JT Dev

I think you can safely use flex :)
Just an example of how you can do without it.

P.S. Here described how to do it with Flex dev.to/jetthoughts/vertical-align-...

Collapse
 
frankwisniewski profile image
Frank Wisniewski

The last example does not center vertically

Collapse
 
jetthoughts_61 profile image
JT Dev • Edited

It centers the element div
jsfiddle.net/7topmk90/1/