skip to Main Content

The parent div is set to ‘vertical-align: top;’ and the child div is set to ‘vertical-align: middle’ but the child is still aligning to the top. How do I make the child align to the middle relative to the height of the parent. I don’t know the specific height of the elements, so I can’t move them based on their height.

#parent {
  vertical-align: top;
  display: inline-block;
  height: 1em;
  width: 20px;
  position: relative;
  background-color: rgba(100,100,100,0.2);
} 

#child {
  vertical-align: middle;
  display: inline-block;
  height: 2em;
  width: 5px;
  background-color: blue;
}
<div id="parent">
  <div id="child">
  </div>
</div>

3

Answers


  1. I think Flexbox would be more appropriate. You could declare align-items on the parent or align-self on the child element.

    #parent {
      display: flex;
      align-items: center;
      height: 1em;
      width: 20px;
      background-color: rgba(100,100,100,0.2);
    } 
    
    #child {
      height: 2em;
      width: 5px;
      background-color: blue;
    }
    <div id="parent">
      <div id="child">
      </div>
    </div>
    Login or Signup to reply.
  2. Ensure the parent has enough height to accommodate the child

    Login or Signup to reply.
  3. In your code replace display: inline-block with display: flex in #parent & also add align-items: center that’s all.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search