Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

html - Setting the image `width: 0` hides it, while `width: 0%` makes it occupy the space, too

The image inside the container element having a specific display type behaves differently when using the img { width: 0; } or img { width: 0%; } style rules.

Increasing the value of width using any unit other than % gave the same expected result (img occupies only the shown part of it).


I've tried changing the display type of the container the img is in. The result is shown below.

Container display types in which the img is shown not as expected:

  1. -webkit-inline-box
  2. inline-block
  3. inline-flex
  4. inline-grid
  5. inline-table
  6. table
  7. table-cell
  8. table-row
  9. table-row-group
  10. table-header-group
  11. table-footer-group

Not sure how they're related to each other, probably I'm missing something.


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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As @Talmid said in his answer we are facing a complex calculation and using width:0 and width:0% isn't the same.

The first one is an absolute value (a length) that the browser can resolve without the need of any reference but the second one is a percentage value that is relative to the width of the containing block so the browser need to know the width of the containing block first to resolve it. (it will not do the effort to conclude that 0% will be the same as 0)

This issue will happen with all the elements where we have a shrink-to-fit behavior (float, inline-block, etc)

Here is more examples:

img {
  width: 30%;
}

span {
  border: 1px solid;
  display: inline-block;
}
<span>
      <img src="https://picsum.photos/id/1012/200/100">
</span>

<span style="float:left;">
      <img src="https://picsum.photos/id/1012/200/100">
</span>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...