Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically align a child div element with parent div having dynamic height [duplicate]

Tags:

css

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?

like image 760
Optimus Avatar asked Sep 01 '16 12:09

Optimus


People also ask

How do I vertically center a div to a parent?

inner-box, center the image tag horizontally using text-align:center property as it's the inline element. Finally, add vertical-align:middle to the inner div which is pushed to vertically center to its parent element.

How do I vertically align a div?

Use the margin property to make sure that the <div> element is center aligned according to its parent element.

Can a child div be bigger than parent?

The child DIV needs to be the same width as the browser viewport. The child DIV must stay as a child of the parent div.

How do I align my child div horizontally?

We can set the child element as an in-line element, display: inline-block; , and then set the father element as text-align: center; , so that the child element can be horizontally centered.


1 Answers

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>
like image 180
Lazar Ljubenović Avatar answered Oct 09 '22 07:10

Lazar Ljubenović