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?

1

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

8 Comments

don't use flex . flex have various issues in browsers use these- jsfiddle.net/c1rk2q37
That solution is super hackish. What is the problem with flex-box? It's supported pretty well and works in this simple case in all major browsers.
@Lazar...super cool link..
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..
@lazar..thanks...display:flex with some changes worked for me...
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.