2 Replies - 251 Views - Last Post: 16 June 2020 - 05:03 AM

#1 epoch+5   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 27-April 20

Benefits of using CSS attribute selectors

Posted 15 June 2020 - 02:47 PM

Hi guys

busy doing a 6 hour CSS course and 1 and a half hours in i get the picture of how this stuff works.

but im having a problem understanding the practicality or advantages of using specific selectors etc over classes and ID's.

I know i can 1 off style something using an ID and style multiple things with classes

then the tutorials started going into pseudo classes and attribute selectors like styling images as follows:

img [src^="../img/"]

which apparently styles all images in that directory

would it not be more practical and easier to just make a class called my-images and put that on all images you want to use.

im just finding the practical application with a lot of this stuff a bit abstract.

I hope you understand what i mean...

Is This A Good Question/Topic? 0
  • +

Replies To: Benefits of using CSS attribute selectors

#2 Martyr2   User is offline

  • Programming Theoretician
  • member icon

Reputation: 5549
  • View blog
  • Posts: 14,557
  • Joined: 18-April 07

Re: Benefits of using CSS attribute selectors

Posted 15 June 2020 - 09:31 PM

What if you had 100 images? Would you like to hand code every image to put on a class? That sounds like a lot of repeat code and tedious.

There will be times where you need to style based on various factors. Position (where in the hierarchy), custom classes or IDs, sometimes you want to target a specific tag and sometimes you want to target multiple elements that share some kind of attribute. Sure you can target based on the src attribute, but perhaps you want to target based on the data attribute (something to look up when you have a chance). Sometimes it is because you don't control the HTML (maybe it is coming from a platform you are working with... think a CMS or web builder).

While I find it rare to target based on much other than classes and IDs, it does happen from time to time. It really helps when you are inside a web tool and need to target some HTML you didn't exactly create. Maybe it is part of a web template that was generated by some platform. If you don't have control of the actual HTML being generated, how can you add a class attribute? Often times it also helps reduce the amount of code you have to setup. As I stated at the beginning of this post.

It has its uses for sure... it is just not as common as classes and IDs I find. :)
Was This Post Helpful? 1
  • +
  • -

#3 epoch+5   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 27-April 20

Re: Benefits of using CSS attribute selectors

Posted 16 June 2020 - 05:03 AM

Thanks for that Martyr2 brilliantly explained!!!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1