Element with “display: inline-flex” has a strange top margin

前端 未结 1 1956
谎友^
谎友^ 2020-12-05 19:31

I have two div elements, both with the CSS property display: inline-flex, as I would like to position them beside each other. At first, the div\'s

1条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 20:23

    With display: inline-flex you are dealing with inline-level elements.

    This activates the vertical-align property, which applies only to inline-level and table-cell elements (source).

    The initial value of vertical-align is baseline. This means that inline-level elements position themselves vertically to achieve baseline (text) alignment.

    baseline

    The baseline is the line upon which most letters sit and below which descenders extend.

    enter image description here

    Source: Wikipedia.org

    This is your current code structure, with the text you added:

    .userImg {
      display: inline-flex;
      height: 3em;
      width: 3em;
      background: red;
    }
    
    .nameOfUser {
      display: inline-flex;
      height: 3em;
      width: 10em;
      background: aqua;
    }

    Jaxon Crosmas

    The second element shifts down so that it aligns with the current baseline of the first element.

    Now add some text to the first element:

    .userImg {
      display: inline-flex;
      height: 3em;
      width: 3em;
      background: red;
    }
    
    .nameOfUser {
      display: inline-flex;
      height: 3em;
      width: 10em;
      background: aqua;
    }
    text

    Jaxon Crosmas

    Notice how the baselines shift to align.

    The elements still aren't squarely aligned because the h3 has default vertical margins. If you remove the margins:

    .userImg {
      display: inline-flex;
      height: 3em;
      width: 3em;
      background: red;
    }
    
    .nameOfUser {
      display: inline-flex;
      height: 3em;
      width: 10em;
      background: aqua;
    }
    
    h3 { margin: 0; }
    text

    Jaxon Crosmas


    Here are two quick solutions:

    1. Override the default value of vertical-align, with any other value.

    .userImg {
      display: inline-flex;
      height: 3em;
      width: 3em;
      background: red;
    }
    
    .nameOfUser {
      display: inline-flex;
      height: 3em;
      width: 10em;
      background: aqua;
    }
    
    div { vertical-align: top; }

    Jaxon Crosmas

    2. Make the parent a flex container.

    This makes your elements flex items, which de-activates vertical-align since flex items are block-level elements.

    This method also lines up your elements in a row, because an initial setting of a flex container is flex-direction: row.

    .userImg {
      height: 3em;
      width: 3em;
      background: red;
    }
    
    .nameOfUser {
      height: 3em;
      width: 10em;
      background: aqua;
    }
    
    body { display: flex; }

    Jaxon Crosmas

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