Why does this inline-block element have content that is not vertically aligned

前端 未结 4 1159
一向
一向 2020-11-22 07:30

Came across a weird CSS issue. Can someone explain why the box having content is not vertically aligned?

If you put text inside the span with class .divPutText

相关标签:
4条回答
  • 2020-11-22 07:55

    try this

    .divPutTextToFixIssue {
       display:inline-block;
     }
    

    jsFiddle

    0 讨论(0)
  • 2020-11-22 08:06

    The default vertical-align value is baseline which

    Aligns the baseline of the box with the baseline of the parent box

    Note: You can see this default value in action by adding vertical-align:baseline to your .divAccountData selector. Since baseline is default the alignment is unchanged.

    You need to change it to top to align the blocks at the top, for example:

    .divAccountData {
        display: inline-block;
        background: red;
        width: 400px;
        height: 40px;
        vertical-align: top;
    }
    

    Baseline is defined as

    the line upon which most letters "sit" and below which descenders extend

    To address why adding text seems to fix the problem it is because

    The baseline of an 'inline-block' is the baseline of its last line box in the normal flow, unless it has either no in-flow line boxes or if its 'overflow' property has a computed value other than 'visible', in which case the baseline is the bottom margin edge.

    from CSS2 Visual formatting model details

    So adding just a single character changes the baseline, causing the second block to appear at the same vertical alignment. This only works if both blocks contain the same number of lines. Try adding more words to one of your blocks and you will see that without forcing vertical-align:top on the second block it will move depending on how many lines of text exist in the first block.

    Edit: Found a related question Why is this inline-block element pushed downward?

    0 讨论(0)
  • 2020-11-22 08:06

    You need to add vertical-align: top; to .divAccountPicker demo

    0 讨论(0)
  • 2020-11-22 08:06

    Add vertical-align:top in your .divAccountData, .divAccountPicker class as like this

    .divAccountData, .divAccountPicker {
        vertical-align: top;
    }
    

    LIve demo

    If you used to display:inline-block; than used to all-ways vertical-align:top

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