cssblockdisplay

Why does an empty child element with display: inline-block create space in its parent element?


Here is a parent element which has a child, the parent element does not have any width or height property but the child has 100% percent width and height and display: inline-block .

HTML and CSS

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .parent {
        background-color: red;

      }
      .child {
        display: inline-block;
        width: 100%;
        height: 100%;
        background-color: black;
      }
    </style>
  </head>
  <body>
    <div class="parent">Hello
      <div class="child"></div>
    </div>
  </body>
</html>

I didn't expect the child to take any space because it is empty and the parent does not have width and height but it makes a empty space in the parent .

enter image description here

I can use display block to fix this but i just want to know why this happens when display inline-block is used ?


Solution

  • The parent element has a line-height. By giving the child element 100% width, you're guaranteeing that it will be on line on its own. Because it's empty, it has 0 height (the 100% height has no effect because the parent element does not have a definite height), but the line in which it resides has the height of the parent's line-height. So the parent has the height of two lines.