I am curious to know, is it true that it is better to assign a class name to the <img> tag in the html file instead of writing it down directly into css file?
<div> <img alt="" /> <img alt="" /> <img alt="" />
</div>instead of
.column img{/*styling for image here*/}I need to know is there any differences between of these in terms of web performance?
UPDATE:
I'm sorry, supposely the question is multiple <img> tags inside the .column div and all the images are using the same styling.
5 Answers
The short answer is adding a class directly to the element you want to style is indeed the most efficient way to target and style that Element. BUT, in real world scenarios it is so negligible that it is not an issue at all to worry about.
To quote Steve Ouders (CSS optimization expert) :
Based on tests I have the following hypothesis: For most web sites, the possible performance gains from optimizing CSS selectors will be small, and are not worth the costs.
Maintainability of code is much more important in real world scenarios. Since the underlying topic here is front-end performance; the real performance boosters for speedy page rendering are found in:
- Make fewer HTTP requests
- Use a CDN
- Add an Expires header
- Gzip components
- Put stylesheets at the top
- Put scripts at the bottom
- Avoid CSS expressions
- Make JS and CSS external
- Reduce DNS lookups
- Minify JS
- Avoid redirects
- Remove duplicate scripts
- Configure ETags
- Make AJAX cacheable
Source:
So just to confirm, the answer is yes, example below is indeed faster but be aware of the bigger picture:
<div> <img alt="appropriate alt text" />
</div> 2 It's just more versatile if you give it a class name as the style you specify will only apply to that class name. But if you exactly know every .column img and want to style that in the same way, there's no reason why you can't use that selector.
The performance difference, if any, is negligible these days.
Assigning a class name and applying a CSS style are two different things.
If you mean <img>, and
.someclass { [cssrule]
}, then there is no real performance difference between applying the css to the class, or to .column img
Its depend. If you have more than two images in .column but you only need some images to have css applied then its better to add class to image directly instead of doing .column img{/*styling for image here*/}
In performance aspect i thing apply class to image is better because by doing so css will not look for possible child image.
I think the Class on img tag is better when You use the same style in different structure on Your site. You have to decide when you write less line of CSS code and HTML is more readable.