开发者

HTML5 - Can I use Width and Height in IMG?

开发者 https://www.devze.com 2023-03-21 23:09 出处:网络
It is Legal to use this code: <img src=\"...(here image)....\" width=\"50px\" height=\"50px\" 开发者_如何学编程/>

It is Legal to use this code:

<img src="...(here image)...." width="50px" height="50px" 开发者_如何学编程/>

Or I need to use:

<img src="...(here image)..." style="width: 50px; height: 50px;" />


First use is recommended as hints for the browser's rendering, second one works.

In the first form you must not add 'px'.

http://www.w3.org/TR/html5/embedded-content-0.html#dimension-attributes


According to the HTML 5 specification:

The width and height attributes on img ... may be specified to give the dimensions of the visual content of the element

Source: http://www.w3.org/TR/2011/WD-html5-20110113/the-map-element.html#dimension-attributes

Also according to the HTML 5 specification, all elements may have style attributes. Source: http://www.w3.org/TR/html5/elements.html#the-style-attribute

Therefore, since both are allowed, you are free to choose whichever one suits your fancy.


CSS applied to 'img' will overwrite basic html width & height attributes on image tags.

<style>
   img {
      width: 100%;
      height: auto;
   }
</style>

<img src="assets/img/logo.png" width="500" height="100">

The above code will result in an image that stretches across the entire width of its container, and its height will be relational to its width.

This approach is helpful if you're loading retina-appropriate graphics from the get-go.


As already mentioned :

  • CSS overwrite <img> attrinutes in case where both are present,
  • <img> attrinutes are only hints for the browser.

Another difference is the use of units :

  • in HTML5 the width and height attributes should be integers without units, that are interpreted as CSS pixels. In practice the brouwsers tolerate % (that was valid in HTML4), but if you put something like width="5cm" it will be interpreted as width="5" (i.e. 5px).
  • When you use CSS, any length units and non integer numbers are allowed, for example width: 5.5cm is ok. And you should use units (for example width: 5 is not a valid CSS width).

So, IMO, you should use CSS if possible.


The style= way is preferred...actually it would be even better if you moved that styling out into a css file or a style tag in your header.


Google Pagespeed Insights recommends the first one to reduce layout shifting. As others have mentioned, it can be overridden easily with CSS, e.g. for responsive pages.

Also, HTML 5 doesn't support self-closing tags (/ at end) so best format would be:

<img src="...(here image)...." width="50" height="50">

0

精彩评论

暂无评论...
验证码 换一张
取 消