【问题标题】:<hr> inside container with display flex become corrupted<hr> 显示 flex 的容器内已损坏
【发布时间】:2016-03-25 17:34:50
【问题描述】:

这种行为有点奇怪和怪异。如果有一个容器,其display 属性设置为flexflex-direction 设置为column,则其中的&lt;hr&gt; 元素的方向将改变并变为垂直,并且其高度将减小以适应行。

html, body {
  height: 100%;
}
body {
  font-family: sans-serif;
}
.container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  flex-grow: 1;
}
<div class="container">
  <h3>Title</h3>
  <hr/>
  <div class="content">
    <p>This is some content</p>
  </div>
</div>

查看this pen

此行为在 Firefox 和 Chrome 上得到确认。我没有找到任何解释。我该如何解决?

【问题讨论】:


  • 放入 div 或 span 对我有用

标签: css flexbox


【解决方案1】:

尝试将您的hr 包含在另一个弹性项目(如divspan 或其他内容)中,如下所示。这将解决您的问题。

之所以可行,是因为弹性盒容器的所有子项都是弹性项目。所以在你的情况下hr 是一个弹性项目。这就是它的造型受到影响的原因。当您将此 hr 设为弹性盒容器的孙子时,它将不再影响其样式。

这就是我们添加&lt;div&gt; 作为&lt;hr/&gt; 的父级的原因。 &lt;div&gt; 成为你的弹性容器的弹性项目。 &lt;hr&gt; 不再是弹性项目。

html, body {
  height: 100%;
}
body {
  font-family: sans-serif;
}
.container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  flex-grow: 1;
}
<div class="container">
  <h3>Title</h3>
  <div><hr/></div>
  <div class="content">
    <p>This is some content</p>
  </div>
</div>

进一步阅读(强烈推荐):

【讨论】:

    【解决方案2】:

    根据HTML5 Rendering - The hr element,预计会用这种风格渲染:

    hr { color: gray; border-style: inset; border-width: 1px; margin: 0.5em auto; }
    

    具体请注意margin-left: automargin-right: auto

    这些样式用于将块元素水平居中。根据Calculating widths and margins - Block

    如果margin-leftmargin-right 都是auto,则它们使用的值 是平等的。这使元素相对于 包含块的边缘。

    在块布局中,只有当块具有明确的宽度时,这种效果才会显着,否则块将增长到覆盖其所有包含块。

    在 Flexbox 中是类似的:默认的 align-self: autoalign-items: stretch 使弹性项目增长到覆盖交叉轴上的弹性线(列布局中的水平线)和 auto margins can also be used to center

    但是,有一个很大的区别:根据Cross Size Determinationalign-self: stretch 不影响具有auto 边距的弹性项目:

    如果一个弹性项目有align-self: stretch,它的计算交叉大小 属性为auto,其横轴边距均不是auto, 使用的外部交叉尺寸是其柔性线的使用的交叉尺寸, 根据项目的最小和最大交叉尺寸属性进行固定。 否则,使用的十字尺寸是项目的hypothetical cross size

    然后,您可以通过删除auto 边距来解决此问题:

    hr {
      margin-left: 0;
      margin-right: 0;
    }
    

    .container {
      padding: 20px;
      display: flex;
      flex-direction: column;
    }
    hr {
      margin-left: 0;
      margin-right: 0;
    }
    <div class="container">
      <h3>Title</h3>
      <hr />
      <div class="content">
        <p>This is some content</p>
      </div>
    </div>

    另外,通过widthmin-width 强制一定宽度可以抵消由auto 边距引起的收缩(从技术上讲,是缺乏拉伸)。

    【讨论】:

    • 这个解释完全有道理,谢谢。我应该先参考规格。现在这是正常行为,而不是浏览器错误或 flexbox 模型的问题。
    • @ahmadalfy 看看我的回答是否有帮助。 :)
    • 很好的答案!但是在 chrome 中,用户代理似乎覆盖了 margin: 0; 并且没有任何反应。有人也有吗? (如果我将样式内联在 html 中,它会起作用,我错过了什么吗?)
    【解决方案3】:

    我发现设置&lt;hr&gt; 的宽度也可以100% 解决问题。还是很奇怪,我不知道为什么会这样。

    Here is a pen

    【讨论】:

    • @ahmedalfy 您可能想查看下面给出的答案。
    • 谢谢,这对我有用。我有 hr 元素作为 flex box 元素的子元素,并且设置宽度 100% 有效!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    相关资源
    最近更新 更多