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
2.2k views
in Technique[技术] by (71.8m points)

css - Why does width/height work on an inline img element

It is my understanding that inline elements can't usually be sized using CSS width and height properties. It seems that an inline img is an exception to this, and that you can resize it using width and height.

img {
  display: inline;
  height: 35px; // this works
}

I'd like to understand if this is something specialized to an img tag, or if there is some other nuance that makes this work.

Can someone point me towards some spec or documentation that describes this behavior?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

an img is an inline replaced element unlike span for example which is an inline non-replaced element and we can define width/height on replaced element. Here is the relevant part of the specification that define how height/width should behave

https://www.w3.org/TR/CSS2/visudet.html#inline-replaced-width

https://www.w3.org/TR/CSS2/visudet.html#inline-replaced-height

When it comes to non-replaced elements you will find this:

The 'width' property does not apply. ref

The 'height' property does not apply. ref


Same logic apply to tranformation where we can apply transformation to img and not span.

Related: CSS transform doesn't work on inline elements


https://developer.mozilla.org/en-US/docs/Web/CSS/Replaced_element

https://html.spec.whatwg.org/multipage/rendering.html#replaced-elements


Note that in the specification it's also said that inline-block replaced element are exactly the same as inline replaced element so setting inline or inline-block to the img will make no difference.


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

...