Is setting image dimensions with CSS as "good" as setting them in HTML? - html

When I was first learning HTML a very long time ago, I was told that it was important to always set the dimensions of your images in your HTML, so that browsers could draw an empty box where the image should go, render your page, and then download and render the images where they belong. If you didn't set width and height values for your images, the browser would have to download the images first to discover their dimensions, and it would slow page loading for people with crappy connections.
For the past few years I've been using CSS, I always put a width and height declaration in my img tags in my HTML. My question is, is setting width and height in the style sheet, and no longer adding these HTML attributes, just as good? It certainly makes my spartan HTML look even cleaner without them.

The problem you mention with the image not being downloaded immediately also applies to your CSS.
The difference is that without the rest of the CSS the whole layout may not make sense. In other words, if the rest of the CSS hasn't loaded then the fact that the image dimensions are also missing won't really be that noticeable.
So personally I think it's fine to put the dimensions in the CSS.

This is a good question, but it's a bit subjective and may lead to more discussion than is generally advised on SO.
Back in the 90's, browsers were slow, and so was the internet. 56k took a while to transfer medium sized images. During that time, the layout would resize to fit the image.
Fast-forward a decade, and internet speeds are much faster, rendering times are much faster. People are used to layouts that change a bit in the first half-second of page load. It's not bad to not specify an image size, as long as you understand the layout of the page may shift during loading.
CSS is parsed before the page is loaded, so specifying the height & width in CSS will work just as well as specifying it inline.
One thing to keep in mind is that inline styles (and that includes height and width declarations) always trump CSS in specificity. If you specify heights and widths of images inline, you may have to go back through every page where an image is present if you want to adjust the size of the images.
Personally I'd suggest using CSS, as it keeps all your styles in the same place.

Yes, setting these properties in CSS will work just as well.
I don't know that it affects page rendering speed in any manner, however. The little effect it does have, is that layout that depends on the image will appear to jump around on the page until the image is loaded and allocates all the space it eventually will.
This is not a practice I follow myself.

A similar question has already been discussed and answered here:
Image width/height as an attribute or in CSS?
It should be defined inline. If you
are using the img tag, that image
should have semantic value to the
content, which is why the alt
attribute is required for validation.
If the image is to be part of the
layout or template, you should use a
tag other than the img tag and assign
the image as a CSS background to the
element. In this case, the image has
no semantic meaning and therefore
doesn't require the alt attribute. I'm
fairly certain that most screen
readers would not even know that a CSS
image exists.
This is also helpful:
If it's part of your site template,
I'd place it in the CSS file.
If it's just on one page, it should be
inline (or defined in a block of
page-specific CSS at the top).

I think the only difference is that css can (yeah it's possible!) not to be read, so <img> attributes are used.
But I'm not sure, I'm going to check that.
EDIT: http://www.mezzoblue.com/archives/2005/05/10/image_attrib/

While you can use CSS to clean up the layout, if your layout messes up by inability to load a single image you should fix that first.
Modern layouts should be controlled by divs and CSS, images in the layout should be supplied only in the form of a background-image:

The reason for always putting the dimensions into HTML code back in the day was due to loading times -- on a 14.4K modem, even relatively small image files would load noticably after the main HTML document had loaded.
These days this is much less of an issue. If it is an issue, it's worth noting that a CSS file will load after the main HTML document, so if you only specify your dimensions there you could potentially suffer the same problem, but CSS files are typically fairly small, so the effect should be minimised.
The other point is that old-school HTML design was very focused on layout, and image sizes were often a critical part of that - if the images were the wrong size, the layout of the whole page would often be completely wrong.
Modern page design approaches things very differently, putting minimal of any layout information into the HTML, and abstracting it all to the stylesheet. Therefore on a typical modern site, until the stylesheets have loaded, the site will just be a series of blocks, and be completely lacking in design. In fact, often the graphics themselves - not just their dimensions - are defined in the stylesheet.
So the answer is that to follow modern page design methods, you should put it in the stylesheet.
Obviously it's critical for most sites these days that the stylesheets load quickly, but it isn't just the size of the graphics that it'll affect.

Related

Responsive images vs Lighthouse performance audit

I'm working with a responsive design and Lighthouse keeps telling me "Image elements do not have explicit width and height". I concluded that it means in the html, because my images have set dimensions in my css with different breakpoints.
Is there a best practice here to keep being responsive but make Lighthouse happy? It might be obvious, but as a student, I'm scratching my head here.
you are right that's actually the best practice and that is recommended for Web Vitals to enhance performance.
If you set height and width, 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.
when you add img in general you should add in html width and height and I prefer to add values that I am adding in CSS or sometimes when I don't have values in CSS I'm doing inspect on the element and make the browser tell me width and height then I back to html and write them.
if you are interested in this topic (Performance) search about Web Vitals (Cumulative Layout Shift) you will find interesting topics

Img as background-image

Can I make the img tag use the background-image properties? Like for example, I have these two pages here one has img and the other one has background-image tag. Notice in responsive version the img one squeezes the image, while the background-image one adjusts the image according to the size.
Page with IMG tag
Page with background-image tag
You can find both img and background-image in sub-header div ..
This'll sound a bit pedantic, but there are a few reasons for it.
An <img> element represents content on the page, something intrinsically important to see and understand. Background images are fluffy stuff to make the site look pretty but their removal would not impact the message.
You are mixing your use-cases. You should go with a background-imaged header in this case because the image isn't intrinsic to the message or content of the page.
Use an <img> element when you're displaying a graph, a photo someone took, etc.
Why?
The browser intentionally treats them differently, as you've noticed, placing a higher priority on showing the content of an <img> tag for example. It'll attempt to stretch the image to fit by default, while a background will simply be clipped.
When the user goes to print the page, it's much easier to remove background images via CSS media queries then it is to hide (the correct) IMG tags.
Background images also don't take up space in the DOM and cause fewer conflicts with other elements. IMG tags flow in the document and can easily get dislodged from their intended position (creating a lot of extra work to make them stay put).
Right-clicking a background image doesn't do much. Right-clicking an image gives you image related options, such as downloading or opening the image. This goes along with the theme of the <img> tag as content.
There are other reasons, but this all boils down to semantics. This may not seem like a big deal to you, but that's probably because you don't have a vision impairment (so you don't regularly use a screen reader) and aren't really thinking about web crawlers and the many other systems that attempt to extract meaning from the tags you've used.
You will be far better off for many, many reasons if you stop fighting the system and use it the way it was intended. Or, at least, know why you're bucking convention before doing so.

will there be a performance issue if i use background images

I came to know that, if we dont give width and height attr. in image tag there will be a performance isssue.
I have a div element for which i'm setting width and height in percentages. Also the same div is having a background image of fixed size say 140px * 140px.
Here, will there be a perfromance issuse?.
markup example:
<div style="width:50%;background:url('imgofsize140*140') no-repeat"> </div>
Thanks
This isn't a one-size-fit-all case - Therefore we have to look at it case by case.
There are a lot of variables that we must keep in mind - User's internet connection speed, image size, computer capabilities, etc.
I found a few questions on SO that are somewhat relevant to this question. I will include them as I see it beneficial. I am NOT claiming to be absolutely correct.
BGIMG vs IMG
Performance Argument
AFAIK, browsers cache images the same whether they're in a DIV or an
IMG. In any case, I think this one of those cases where specific
performance is defined as an implementation detail internal to each
rendering engine (and possibly the browsers built around them). As
such, it's both out of our control as designers/developers and subject
to change from browser to browser and version to version. In other
words, I wouldn't spend too much time worrying about it.
Context
Technical differences yes, most notably you can set the width/height
of an IMG tag and it will stretch the image, which can be useful in
some situations.
The main thing you've got to keep in mind though is the context of the
image within the HTML document. If the image is content, say an image
in a gallery, I'd use a IMG tag. If it is just part of the interface I
might use a div instead.
- By Paul
And the response to that is just as important.
That said, you bring up an excellent point about the semantic
difference: an IMG is usually the better choice when the image is a
material part of the page's content, while a CSS technique is usually
preferred when the image is just decorative or for formatting.
This is not performance related directly - More about semantics and accessibility. By - Mr. W.
Then one more for Performance OFF of SO which I feel is directly related to your question.
Page Load Test
The version with background images actually gave me a “Document
Complete” after .0225 seconds – while the fully loaded page load time
was roughly the same as the inline image version. Could using all
background images speed up firing of $.document(ready)? It turns out
background-images are only downloaded after the element (containing
div, span etc) is available. This prevents blocking from all the round
trips required to get images.
results: inline image test page
results: background image test page
I wouldn't think there would be a performance issue in the same way as not specifying height and width on a img tag, since that forces the browser to repaint the whole page and that's where the performance issue is.
http://code.google.com/speed/page-speed/docs/rendering.html#SpecifyImageDimensions
tl;dr
You will not get a performance penalty (which is really small in the other case as well).
Some more details:
You shouldn't care (unless you work for Google) about the performance "penalty" you'd get from not specifing a width & height, but more about the layout flickering you might get.
Not specifing a width and height will make the browser display an initial box, as it doesn't know beforehand how much space the image will take, and after the image is loaded it will do a reflow - which means it will have to recalculate the layout of some elements which will be affected by the size change. But, this is actually going to happen very fast (and you're probably triggering reflows in lots of other places).
There is no reflow necessary for the background image.
I don't think this will effect perfomance.
If you combine your background images into one image and position it as and when you need to that will help speed up performance as you're only loading the one image rather than multiple images.
The background image will be displayed as 140x140 unless the div width has smaller size than 140px.
You might also want to check the result in older browsers such as InternetExplorer 6-7-8 just to ensure if there is any other performance issue.
Depends on the browser. I learned today that Chrome currently redraws the canvas as you scroll with an absolute position bg image. Firefox handles it just fine. This should be fixed in a future Chrome release.
On the contrary, specifying the img height and will cause the performance issue.
Because by specifying them, you tell the browser to resize the img first, then render the image. For example, storing thumbnail image is much better than resize the image on the fly.
If your image is already the specified size you want their is no need to specify the Height and Width in the attributes. Also, there will be no performance issue in using the background image.

is there a good reason to define widths and heights for images I don't intend to resize?

Just wondering what the best practice is in HTML. I have noticed that I tend to removed the width and height attributes, because they are a pain when I tweak an image, so best to only use if necessary.
Is this best practice? I am I incurring performance issue? Is this legacy stuff?
If you specify the size, browsers can render the page with proper spacing even before loading the images.
I'd say it's good practice to leave the width and height attributes in so that the page doesn't keep shifting around as the images load. In fact, it annoys me quite a bit when I'm trying to view a gallery and they've omitted these attributes! I suppose you could do it with CSS instead, or put the width/height on some container element... just keep in mind that the images will "expand" once the client finishes downloading them and their dimensions can be known.
It can be useful to have the image size so that they page layout can be done before the image is loaded. Otherwise the page renderer doesn't know how much room an image will take up until it knows the size of the image, and this can result in a lot of shifting around as the page loads.
This may not be a big deal for content images, but it can be distracting for images that have an impact on your page layout such as in headers, footers and sidebars.
As Archonix said in his comment, Google has a good overview.

Is it better/faster to resize an image with CSS, or with the <img> tag?

I was wondering what is the better/faster way to resize an image.
Normally I would resize an image with CSS, but a college told me that by using the width attribute, e.g.
<img width="size" [..]>
the browser would render the page faster.
Anyone know if this is true?
It would be even faster if you resized the actual image, and not the dimensions you want the browser to render it to.
You should set width and height properties of each img tag. It speeds up rendering page because browser doesn't wait for css files and images loaded.
width and height are semantic in the case of imges and objects. They provide metadata for images so it is completely fine IMO to rely on those attributes in order to tell the user agent that it should presize the element to X dimensions prior to the image fully rendering.
If we stick with presentation vs. structure, I'd put your image sizes in CSS. Speed really doesn't matter these days, the browser has to wait for the images to be loaded anyway, so the speed it takes to compose and render the page isn't really measureable, well unless your CSS fails to load...
Bit difficult to give definitive answers for very general questions like this, but I think it’s generally better not to resize images in HTML or CSS — make the image file the right dimensions.
Ignoring that, I don’t think there’s likely to be any perceptible difference between the two.