Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a class name to <img> tag instead of write it in css file?

Tags:

html

css

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 class="column">
   <img class="custom-style" alt="" />
   <img class="custom-style" alt="" />
   <img class="custom-style" 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.

like image 374
Qiqi Abaziz Avatar asked Apr 26 '13 04:04

Qiqi Abaziz


2 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) http://www.stevesouders.com/blog/2009/03/10/performance-impact-of-css-selectors/:

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: http://stevesouders.com/docs/web20expo-20090402.ppt

So just to confirm, the answer is yes, example below is indeed faster but be aware of the bigger picture:

<div class="column">
   <img class="custom-style" alt="appropriate alt text" />
</div>
like image 138
Timidfriendly Avatar answered Oct 05 '22 12:10

Timidfriendly


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.

like image 23
Francis Kim Avatar answered Oct 05 '22 13:10

Francis Kim