HTML5 - Can I use Width and Height in IMG?

2019-01-23 23:40发布

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;" />

5条回答
你好瞎i
2楼-- · 2019-01-24 00:06

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.

查看更多
萌系小妹纸
3楼-- · 2019-01-24 00:09

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.

查看更多
神经病院院长
4楼-- · 2019-01-24 00:14

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.

查看更多
等我变得足够好
5楼-- · 2019-01-24 00:17

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.

查看更多
何必那么认真
6楼-- · 2019-01-24 00:25

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

查看更多
登录 后发表回答