代码之家  ›  专栏  ›  技术社区  ›  Danield

为什么容器不扩展以适应其内联元素

  •  2
  • Danield  · 技术社区  · 9 年前

    div 或者 button 其中包含 内联 -容器没有增长到适合内联元素。

    button, div {
      background: blue;
    }
    
    span {
      background: orange;
      /*display: inline-block; */ /* toggle to see container element grow */
      padding: 4em;
    }
    
    hr {
      margin:100px;
    }
    <div>
        <span class="btn__content">
            I'm div inline content
        </span>
    </div>
    
    <hr>
    
    <button class="btn" type="button">
        <span>
            I'm button inline content
        </span>
    </button>

    为什么会发生这种情况?

    注意: 修理 display:flex 这将使容器扩展到内容)

    相反,我正在寻找可靠来源的解释,比如解释内联元素这种行为的规范。

    2 回复  |  直到 9 年前
        1
  •  1
  •   j08691    9 年前

    原因在 Visual Formatting model documentation (我的重点):

    水平边距、边框和填充在这三者之间 盒。这些盒子可以以不同的方式垂直对齐:它们的 线称为线盒。

    线框的宽度由包含块和 浮子的存在。 线路高度计算部分给出的规则 .

    line height

    测线盒的高度确定如下:

    1. 替换的元素、内联块元素和内联表元素, 这是他们的边距框的高度;对于内联框,这是 "Calculating heights and margins" height of inline boxes 在里面 "Leading and half-leading"
    2. 这个 内联水平框根据其垂直方向对齐 它们必须对齐,以最小化线盒高度。如果是这样 盒子足够高,有多种解决方案,CSS 2.1也有
    3. 最上面的盒子顶部和最下面的盒子底部。空内联元素 生成空的内联框,但这些框仍有边距, 计算就像有内容的元素一样。

    MDN 关于长方体模型的注释:

    注意,对于未替换的内联元素,占用的空间量 视觉上围绕内容。

    并由 W3

    “height”属性不适用,但长方体的高度为 由“line height”属性给出。

    https://www.w3.org/TR/REC-CSS2/visudet.html#q15

    button,
    div {
      background: blue;
    }
    
    span {
      background: orange;
      line-height: 10em;
    }
    
    hr {
      margin: 100px;
    }
    <div>
      <span class="btn__content">
            I'm div inline content
        </span>
    </div>
    
    <hr>
    
    <button class="btn" type="button">
        <span>
            I'm button inline content
        </span>
    </button>

    另请参见 Inline elements and line-height

        2
  •  1
  •   Ruan Mendes    9 年前

    设置行高度会更改包含框的高度

    button, div {
      background: blue;
    }
    
    span {
      background: orange;
      /*display: inline-block; */ /* toggle to see container element grow */
      padding: 4em;
      line-height: 8em;
    }
    
    hr {
      margin:100px;
    }
    <div>
        <span class="btn__content">
            I'm div inline content
        </span>
    </div>
    
    <hr>
    
    <button class="btn" type="button">
        <span>
            I'm button inline content
        </span>
    </button>