Empty div vs div with text having inline-block property

后端 未结 4 1173
情书的邮戳
情书的邮戳 2021-02-20 07:49

Want to know the reason for this behavior.

CSS

div {
   display: inline-block;
   margin-right: 2px;
   width: 20px;
   background-color         


        
相关标签:
4条回答
  • 2021-02-20 08:06

    Hi please see here: http://jsfiddle.net/dd24z/ by default text is vertical-align to top but you can change that behavior;

    div {
        display: inline-block;
        margin-right: 2px;
        width: 20px;
        background-color: red;
        vertical-align: bottom;
    }
    

    http://www.w3.org/TR/2008/REC-CSS2-20080411/visudet.html#line-height

    'vertical-align': baseline Align the baseline of the box with the baseline of the parent box. If the box doesn't have a baseline, align the bottom of the box with the parent's baseline.

    0 讨论(0)
  • 2021-02-20 08:06

    I guess this can be explained by the text alignment, independently from divs.

    Text, when placed in a div, is vertically aligned to top-left by default. Those divs without text align beside each other (inline-block) expanding the page downwards. If you add another div, you'll see the second header going further down.

    <h1>Empty div</h1>
    Some text
        <div style="height:20px;"></div>
        <div style="height:40px;"></div>
        <div style="height:60px;"></div>
        <div style="height:80px;"></div>
    continuing here
    
    <h2>Div with text</h2>
    Some text 
        <div style="height:20px;">20</div>
        <div style="height:40px;">40</div>
        <div style="height:60px;">60</div>
        <div style="height:80px;">80</div>
    continuing here
    

    ...

    div {
           display: inline-block;
           margin-right: 2px;
           width: 20px;
           background-color: red;
        }
    

    Fiddle

    In the above fiddle, you can see that the text line is the "guideline".

    Maybe this is the explanation: once the divs have text in them, they will align it with the surrounding text and, if inexistent, then they align their bottom line.

    I'm sorry, maybe not very clear but I hope you understand my view.

    0 讨论(0)
  • 2021-02-20 08:07

    Add

    vertical-align: bottom;
    

    to your CSS. Hope it works as you want.

    0 讨论(0)
  • 2021-02-20 08:09

    Basically it got to do with the way that vertical-align: is calculated. So if you put vertical-aling:bottom; attribute in the css then you will notice it will be the same with and without text.

    you can read the this for more details.

    When the div has no content, padding is not drawn in the box (i.e. when when 0, if there is content, the browser calculates where the padding would be). so there is a little difference in calculating with and without text.

    Hope this is helpfull.

    0 讨论(0)
提交回复
热议问题