css - 高度明确设置为 0 的行内 block 父包装内容

标签 css

JSFiddle demo

在容器元素设置为 display: inline-block 的下拉菜单中,有一个标签(始终可见,切换下拉菜单覆盖)和覆盖元素本身。我将覆盖容器设置为 height: 0 并希望允许覆盖内容超过容器的高度,而不影响任何父元素。但是,我看到了一些奇怪的结果 - 覆盖容器导致下拉菜单的父项也完全包含覆盖内容!

在下面的 HTML 中,ib = 内联 block 和 h0 = height:0 覆盖容器。请参阅 jsfiddle 演示以查看它的运行情况。

<div>
  Sort by this
  <span id="ib">
    <span>LABEL</span>
    <div id="h0">
      DROPDOWN<br />
    </div>
  </span>
</div>

我不想在覆盖层上使用 position: absolute,因为我希望覆盖层的内容决定标签的最终宽度。令人惊讶的是,我可以使用以下 CSS 实现预期的结果:

#ib { display: inline-flex; flex-direction: column; }

我很高兴现在使用该解决方法,但也对这种奇怪效果背后的“原因”感兴趣。

最佳答案

您的问题是关于内联 block 元素的 vertical-align 规则。默认情况下它是 baseline,这里是一些规范:

Baseline: Align the baseline of the box with the baseline of the parent box.

另见:

The height of each inline-level box in the line box is calculated. For replaced elements, inline-block elements, and inline-table elements, this is the height of their margin box; for inline boxes, this is their 'line-height'.

来源:https://www.w3.org/TR/CSS2/visudet.html#line-height

CSS assumes that every font has font metrics that specify a characteristic height above the baseline and a depth below it. In this section we use A to mean that height (for a given font at a given size) and D the depth. We also define AD = A + D, the distance from the top to the bottom.

来源:https://www.w3.org/TR/CSS2/visudet.html#inline-box-height

所以你的修复是通过设置 vertical-align: top/bottom/middle/text-top/text-bottom 由您选择。

固定代码:

.dropdown {
  display: inline-block;
  vertical-align: top;
}

.overlay {
  height: 0;
}
<div>
	sort by this
	<span class="dropdown">
		<span>LABEL</span>
		<div class="overlay">
			DROPDOWN<br />
			  DROPDOWN<br />
			  DROPDOWN
		</div>
	</span>
</div>
<hr />

关于css - 高度明确设置为 0 的行内 block 父包装内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49861868/

相关文章:

html - 为什么响应式设计中的固定宽度侧边栏不起作用?

css - 创建特定宽度的 <div></div> 或带文本换行的 2 行框

html - 覆盖已定义的 CSS 定义?

html - 强制 div 和内容的最大宽度为 100%

html - 使用 CSS 向下移动 LI

html - CSS:对齐 td 内的文本区域

javascript - 尽管导入了变量,但 Winless NameError

html - 包装中未显示背景颜色

html - 如何设置高度?

css - 不是第 n 个子选择器不在 sass 中工作