简体   繁体   中英

Why does a <div> with width not show unless it contains a &nbsp;?

I would like to display a block of color with different widths and no space in between. To test it out I made this HTML but it does not show as a block:

<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>

The only way I could make it work is to add &nbsp. But now I see a space between the color blocks:

<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>

Is there a way I can make a square block without ?

Unless you specify a height, a div is as tall as its content. If it has no content, then it doesn't have any height. If it has no height, then there are zero vertical pixels to give a background colour to.

You need to add a height callout is you want to see an "empty" <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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM