"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why does an empty inline-block div gain height within a hidden container?

Why does an empty inline-block div gain height within a hidden container?

Published on 2024-11-14
Browse:898

Why does an empty inline-block div gain height within a hidden container?

When using inline-block, an empty inline div element within a hidden container curiously gains height. Why does this occur, in contrast to the behavior of display:block?

Display:inline-block imparts specific formatting on the element:

  • Inline-Level Formatting: Elements are laid out horizontally within the container block.
  • Line-Height Calculations: Line-height is calculated differently for inline elements. For inline-block elements, it becomes the height of the margin box. For normal inline elements, it's the 'line-height' property.

When the inline-block element is empty, it assumes its basic line-height, even though there's no font or text content. This results in the element gaining a small but noticeable height, despite its empty state.

A workaround to prevent this height issue is to use a wrapper with font-size:0 to eliminate the line-height calculation:

.wrapper {
    font-size: 0;
}

.wrapper div {
    font-size: medium;
   
}

Update: Understanding Inline-Block Height

Contrary to initial assumptions, the exact height of an empty inline-block element is not officially documented. However, observations and testing suggest that:

  • Inline-block reserves a minimum line space based on the inherited line-height, typically determined by the element.
  • This line space persists even though the inline-block is empty and should theoretically be treated as zero-height according to CSS specifications.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3