skip to Main Content

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 {
        content: "";
        display: 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 ?

3

Answers


  1. Add vertical-align:top to the child element.

    It has to do with the “inline-block” element now resting on the baseline of the line of text as opposed to ignoring it as it does when it’s just “block”.

    Setting the vertical-align:top property pushes its baseline down and removes the little space.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. Probably because all child elements without specifying sizes have by default the maximum proportional sizes of their parents, for example, if you have a div with another div in it, let’s call them div1 and div2.
    div2 without explicitly specified size parameters will take the dimensions of div1, in your case parent receives the size of body in proportion to the sizes of the two elements "Hello" and Child
    to put it simply, without explicitly specified size parameters, width = 100% and height is counted from child elements

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