8

How do I vertically align a child element with the parent having a dynamic height.

CSS code:

parent{
    height: 400px;
}
.child{
    position:relative;
    top:50%;
    transform: translateY(-50%;);
}

This sets the child once, then doesn't change. How do I change it so that it changes with the dynamic height of the parent?

Pranjal
  • 1,088
  • 1
  • 7
  • 18
Optimus
  • 93
  • 2
  • 9

1 Answers1

8

You can use display: flex.

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  width: 100px;
  margin: 1em;
  background-color: tomato;
}

.child {
  width: 10px;
  height: 10px;
  background-color: yellow;
}

You can use `displa: flex`.

The following doesn't rely on parent's height.
<div class="parent">
  <div class="child">
  </div>
</div>
Lazar Ljubenović
  • 18,976
  • 10
  • 56
  • 91
  • don't use flex . flex have various issues in browsers use these- https://jsfiddle.net/c1rk2q37/ – moidul dargahi Sep 01 '16 at 12:35
  • That solution is super hackish. What is the problem with flex-box? It's supported [pretty well](http://caniuse.com/#feat=flexbox) and works in this simple case in all major browsers. – Lazar Ljubenović Sep 01 '16 at 12:36
  • 1
    @Lazar...super cool link.. – Optimus Sep 01 '16 at 12:39
  • I think you should read the question first properly, It clearly mentions that the height and width comes dynamically not 100px . Its very easy to set in vertical while you know the width and height.. – moidul dargahi Sep 01 '16 at 12:40
  • @moiduldargahi I specified the height and width because I have to specify _something_. If you change the height and width, it still works. You should test the solution properly. – Lazar Ljubenović Sep 01 '16 at 12:41
  • @LazarLjubenović oh really :P then make the parent div height and width 100% you will get the result – moidul dargahi Sep 01 '16 at 12:43
  • 1
    @lazar..thanks...display:flex with some changes worked for me... – Optimus Sep 01 '16 at 12:45
  • @moiduldargahi You cannot set it to a `100%` in the code snippet here because `100%` means `100%` of **its parent**, and the parent of `.parent` has no specified size. You can fiddle with the width and height and see that, no matter what you change it to, it will remain in the perfect center. The code doesn't reply on `width` and `height` properties of `parent`. – Lazar Ljubenović Sep 01 '16 at 12:46