为什么宽度不显示的<div>除非它包含?</div>

时间:2015-02-08 17:40:20

标签: html css

我想显示一个不同宽度的颜色块,中间没有空格。为了测试它我制作了这个HTML,但它没有显示为块:

<div style="text-align: left;">
   <div style="display:inline-block;background-color:green; width:0rem;"></div>
   <div style="display:inline-block;background-color:red; width:0.3rem"></div>
   <div style="display:inline-block;background-color:yellow; width:0.9rem"></div>
</div>

我能让它发挥作用的唯一方法就是添加&amp; nbsp。但是现在我在颜色块之间看到了一个空格:

<div style="text-align: left;">
   <div style="display:inline-block;background-color:green; width:0rem;">&nbsp;</div>
   <div style="display:inline-block;background-color:red; width:0.3rem">&nbsp;</div>
   <div style="display:inline-block;background-color:yellow; width:0.9rem">&nbsp;</div>
</div>

有没有办法可以制作方形块?

2 个答案:

答案 0 :(得分:5)

除非您指定高度,否则div与其内容一样高。如果它没有内容,那么它没有任何高度。如果它没有高度,则零垂直像素可以给出背景颜色。

答案 1 :(得分:2)

你需要添加一个高度标注你想看到一个&#34;空&#34; <div>Like this.

<div style="text-align: left;">
   <div style="display:inline-block;background-color:green; height:0.5rem;width:0.5rem;"></div>
   <div style="display:inline-block;background-color:red; height:0.5rem;width:0.3rem"></div>
   <div style="display:inline-block;background-color:yellow; height:0.5rem;width:0.9rem"></div>
</div>