【发布时间】:2026-01-12 15:55:01
【问题描述】:
使用img { width: 0; } 或img { width: 0%; } 样式规则时,具有特定display 类型的容器元素内的图像表现不同。
使用除 % 以外的任何单位增加width 的值会得到相同的预期结果(img 仅占其中显示的部分)。
我尝试更改img所在容器的display类型。结果如下所示。
img 显示的容器display 类型不像预期的那样:
- -webkit-inline-box
- 内联块
- 内联-flex
- 内嵌网格
- 内联表
- 表格
- 表格单元格
- 表格行
- 表行组
- 表头组
- 表格页脚组
不确定它们是如何相互关联的,可能我遗漏了一些东西。
button:first-of-type img {
width: 0;
}
button:last-of-type img {
width: 0%;
}
<h3>The image width: 0 (hides it)</h3>
<button>
<img src="https://picsum.photos/id/1012/200/100">
<p>Add playlist</p>
</button>
<h3>The image width: 0% (occupies the space (natural img width) and hides it)</h3>
<button>
<img src="https://picsum.photos/id/1012/200/100">
<p>Add playlist</p>
</button>
img { width: 0%; } 应该像 img { width: 0; } 一样工作而不占用任何空间,但这里不是这种情况。
【问题讨论】:
-
我很困惑你想在这里实现什么。如果您不想显示图像,为什么要首先包含它?
-
我只是好奇它为什么会这样。另外,尝试将
0%更改为,比如说30%。您将看到占用空间保持不变,而图像大小更改为父容器的30%。 -
有什么想法吗,伙计们?
-
这是个好问题。希望我现在有时间研究它。请注意,差异似乎仅适用于图像元素。如果你在其他元素上尝试
width: 0/width: 0%,比如button父元素,渲染是一致的。 -
@Michael_B 不仅是图片,请查看我的答案