I have read a lot that you should separate your css styling from your content, and that using inline styling isn't the best practice, but is this the same with the size of <img>
tags?
Is it the best practice to set the width and height using attributes, or is it best to put it in a css class?
<img src="myimg.png" height="100" width="200" />
or
.myimg{
height:100px;
width:200px;
}
<img src="myimg.png" class="myimg" />
or is there no 'best' practice? if so, in which situations should you use 1 or 2?
The height and width of an image can be set using height and width attribute. The height and width can be set in terms of pixels. The <img> height attribute is used to set the height of the image in pixels. The <img> width attribute is used to set the width of the image in pixels.
One of the simplest ways to resize an image in the HTML is using the height and width attributes on the img tag. These values specify the height and width of the image element. The values are set in px i.e. CSS pixels.
Tip: Always specify both the height and width attributes for images. If height and width are set, the space required for the image is reserved when the page is loaded. However, without these attributes, the browser does not know the size of the image, and cannot reserve the appropriate space to it.
The background-size CSS property lets you resize the background image of an element, overriding the default behavior of tiling the image at its full size by specifying the width and/or height of the image. By doing so, you can scale the image upward or downward as desired.
I believe one of the best practices is to avoid inline styling as much as possible, and try to do most attributes by CSS to the biggest extent.
However, when you try and validate HTML, it will often fail if an <img
tag doesn't have height and width stated, so I would include these in the markup wherever possible. It's also a benefit to SEO, for them to be correctly identified for Image Searches.
Another important SEO factor, is to try to avoid linking to fullsize images, and then scaling them down using CSS. If you have an image which is say 3000x2000 and the output will only be 320x250, then you really should create a 320x250 version of the image, upload it, and link to that instead. This will dramatically help your website's load time, and performance.
They're both technically correct, but I would consider the second method to be "best practice" for the same reason as avoiding inline styles - by using classes and CSS, all similar elements match and I can make updates all in one place.
Edit: upvote for Dave - important point about resizing before upload. I agree!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With