这种行为有点奇怪和怪异.如果有一个与它的容器display属性设置为flex与flex-direction对column,对的方向<hr>里面的元素会发生变化,成为垂直和它的高度将降低,以适应该行的高度.
html, body {
height: 100%;
}
body {
font-family: sans-serif;
}
.container {
padding: 20px;
height: 100%;
display: flex;
flex-direction: column;
flex-grow: 1;
}Run Code Online (Sandbox Code Playgroud)
<div class="container">
<h3>Title</h3>
<hr/>
<div class="content">
<p>This is some content</p>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
看看这支笔.
Firefox和Chrome已确认此行为.我没有找到任何解释.我该如何解决?
Ori*_*iol 44
根据HTML5渲染 - hr元素,它应该使用这种样式呈现:
hr { color: gray; border-style: inset; border-width: 1px; margin: 0.5em auto; }
Run Code Online (Sandbox Code Playgroud)
特别要注意margin-left: auto,margin-right: auto.
这些样式用于水平居中块元素.根据计算宽度和边距 - 块
如果这两个
margin-left和margin-right是auto,它们的使用值是相等的.这使元件相对于容纳块的边缘水平居中.
在块布局中,只有块具有明确的宽度时,此效果才会显着,否则块将增长以覆盖其所有包含的块.
在Flexbox中它类似:默认align-self: auto和align-items: stretchmake flex项目增长到覆盖横轴的柔性线(列布局中的水平线),auto边距也可用于居中.
但是,存在很大差异:根据交叉尺寸确定,align-self: stretch不会影响具有auto边距的弹性项目:
如果flex项具有
align-self: stretch,其计算的交叉尺寸属性是auto,并且它的横轴边距都不是auto,则使用的外部交叉尺寸是其柔性线的使用交叉尺寸,根据项目的最小和最大交叉尺寸属性进行夹紧.否则,使用的交叉大小是项目的假设交叉大小.
然后,您可以通过删除auto边距来解决此问题:
hr {
margin-left: 0;
margin-right: 0;
}
Run Code Online (Sandbox Code Playgroud)
.container {
padding: 20px;
display: flex;
flex-direction: column;
}
hr {
margin-left: 0;
margin-right: 0;
}Run Code Online (Sandbox Code Playgroud)
<div class="container">
<h3>Title</h3>
<hr />
<div class="content">
<p>This is some content</p>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
或者,强迫一定宽度通过width或min-width将抵消由auto边缘引起的收缩(在技术上更多,缺乏拉伸).
尝试将您的内容包含hr在另一个弹性项目中(例如div或span其他项目),如下所示。这将解决您的问题。
之所以有效,是因为弹性盒容器的所有子项都是弹性项目。所以在你的例子中hr是一个弹性项目。这就是它的造型受到影响的原因。当您将其设为hr弹性盒容器的孙子时,它将不再影响其样式。
这就是为什么我们添加<div>为 的父级<hr/>。<div>成为弹性容器的弹性项目。<hr>不再是弹性项目。
html, body {
height: 100%;
}
body {
font-family: sans-serif;
}
.container {
padding: 20px;
height: 100%;
display: flex;
flex-direction: column;
flex-grow: 1;
}Run Code Online (Sandbox Code Playgroud)
<div class="container">
<h3>Title</h3>
<div><hr/></div>
<div class="content">
<p>This is some content</p>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
进一步阅读(强烈推荐):