Ahmed Gad Ahmed Gad - 7 months ago 21
HTML Question

CSS: Why h3 drops down its parent div?

There is a simple example where a div element contains h3.

But the h3 element drops down its parent div when h3 has position relative.

Changing h3 position to absolute solves this problem.

What is the reason?





.personal-details{
background-color: green;
}

.personal-image{
display: inline-block;
width: 150px;
height: 150px;
background-color: white;
}

.personal-description {
display: inline-block;
width: 150px;
height: 150px;
background: black;
}


.personal-description h3 {
position: relative; /*absolute solves the problem*/
}

<div class="personal-details">
<div class="personal-image"></div>
<div class="personal-description"><h3 class="name">My Name</h3></div>
</div>




Answer

This is caused by the default vertical-align: baseline; property of inline-block elements.

Overriding the default with vertical-align: top for your element will get you somewhere like correct:

.personal-details {
  background-color: green;
  vertical-align: middle
}

.personal-image {
  display: inline-block;
  width: 150px;
  height: 150px;
  background-color: green;
}

.personal-description {
  display: inline-block;
  width: 150px;
  height: 150px;
  background: black;
  vertical-align: top;
}

.personal-description h3 {
  position: relative;
  background: yellow;
}
<div class="personal-details">
    <div class="personal-image"></div>
    <div class="personal-description"><h3 class="name">My Name</h3></div>
</div>

Notice I say "somewhere like correct" as you will still have issues with space around the elements (notice the gap below the black square and space between the two child divs). But that is out of the scope of your question and has been dealt with many times before.