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"
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
#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
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
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.
- And it's output will look like this-
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
attributes selector
- Will only select the anchor tags that have a title attribute
- Will style all anchor tags which link to http://www.google.com
- 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
- Attribute "contains" value
- Needs to be whole word
- Attribute "contains" value
- Does not have to be whole word
- Attribute "starts with" value
- The value has to be a whole word
- Either whole word
- Or word followed by -
- Attribute "starts with" value
- The value DOEST NOT have to be a whole word
- Attribute "ends with" value
- The value DOEST NOT have to be a whole word
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)
Informative!
Thanks a lot! Will try to post more such blogs soon. :)
Great work Robin!!!!
Thanks Soham!