Why is this inline-block element pushed downward?

前端 未结 8 992
别那么骄傲
别那么骄傲 2020-11-21 04:45

Following is my code and I want to understand that why #firstDiv is being pushed downward by all browsers. I really want to understand the inner wo

8条回答
  •  离开以前
    2020-11-21 05:05

    I originally started on answering this question, but it was locked as dupe before I could finish, so I post the answer here instead.

    First, we need to understand what inline-block is.
    The definition in MDN says:

    The element generates a block element box that will be flowed with surrounding content as if it were a single inline box (behaving much like a replaced element would)

    To understand what's going on here, we need to look at vertical-align, and it's default value baseline.


    In this illustration you have this color chart:
    Blue: The baseline
    Red: The top and bottom of the line-height
    Green: The top and bottom of the inline content box.

    In the #left element, you do have some textual content that controls what is the baseline. This means that the text inside defines the baseline for #left.
    In the #right, there is no content, so the browser has no other option than to use the box bottom as the baseline.

    Se this visualisation where I have drawn the baseline on an example where the first inline container has some text, and the next is empty:

    If you specifically align one element to top, you really say that you align the top of this element to the top of of the line box.

    This might be easier to understand by an example.

    div {
        display: inline-block;
        width: 100px;
        height: 150px;
        background: gray;
        vertical-align: baseline;
    }
    div#middle {
        vertical-align: top;
        height: 50px
    }
       
    div#right {
        font-size: 30px;
        height: 100px
    }
    groovy
    groovy

    The result is this - and I added the blue baseline, and the red line box:
    What happens here, is that the height of line box is depended on how the the content of the entire line is laid out. This means that to calculate the top alignment, the basline alignments must be calculated first. The #middle element has vertical-align:top, so this is not used for the baseline positioning. but the #left and #right are positioned vertically so that their baselines are aligned. When this is done, the height of the line box has increased, because the #right element has been pushed up a bit as a result of the larger font size. Then the top position for the #middle element can be calculated, and this is along the top of the line box.

提交回复
热议问题