DEV Community

Cover image for Master CSS Selectors
Robin Hooda
Robin Hooda

Posted on • Updated on

Master CSS Selectors

Alt Text

What are CSS selectors?

  • In CSS, selectors are patterns used to select the HTML element(s) on our web pages we want to style.
  • In layman terms, selectors are used to grab a DOM element to apply styles to it

What are different types of CSS selectors?

.class

  • Selects all elements with given class name
  • Write a period (.) character, followed by the name of the class
  • It will select all p with class="myClass"

Alt Text

child .class

  • We can target child element using a class hierarchy
  • We have to write parent class name followed by a space, and then followed by the child's class name
  • Below example will add background-color: yellow to the paragraph

Alt Text

#id

  • Style the element with given id attribute
  • In below example intro is the id of the paragraph
  • We select the elements by adding # followed by the id attribute of the element

Alt Text

element tag

  • We can directly select an element by its tag name and apply the styles
  • In this case we don't have to mention id or the class - simply write the element name in our styles and add properties to it
  • Below example will grab all the p elements and apply the style to it

Alt Text

Mixture of #id, .class and element tag

  • Below example will grab all the h1 elements which have class named heading and id's as greeting and intro respectively.

Alt Text

  • And it's output will look like this-

Alt Text

adjacent selector

  • Selects only the element which is preceded by the former element
  • In this case, only the first paragraph after each h1 will have gray text

Alt Text

attributes selector

  • Will only select the anchor tags that have a title attribute

Alt Text


Alt Text


  • Star designates that the proceeding value must appear somewhere in the attribute's value
  • This covers any links which consists of 'com' in them such as, google.com, gmail.com, wikipedia.com

Alt Text


  • Attribute "contains" value
  • Needs to be whole word

Alt Text


  • Attribute "contains" value
  • Does not have to be whole word

Alt Text


  • Attribute "starts with" value
  • The value has to be a whole word
    • Either whole word
    • Or word followed by -

Alt Text


  • Attribute "starts with" value
  • The value DOEST NOT have to be a whole word

Alt Text


  • Attribute "ends with" value
  • The value DOEST NOT have to be a whole word

Alt Text

If still have any doubts, do drop me a message on my linkedin or twitter

Don't forget to follow me on -

Top comments (4)

Collapse
 
sohamsshah profile image
Soham Shah

Informative!

Collapse
 
robinhooda profile image
Robin Hooda

Thanks a lot! Will try to post more such blogs soon. :)

Collapse
 
sohamparab profile image
soham-parab

Great work Robin!!!!

Collapse
 
robinhooda profile image
Robin Hooda

Thanks Soham!