Last updated on October 31st, 2020 at 07:49 am.
20 Understanding CSS Selectors – Introduction to Selectors
The most important thing in CSS is selectors. I say this because, if your selectors are incorrect, the element you would like to style will not be styled. It is therefore important for you to learn how to use selectors correctly. You should watch the above video for illustrations.
In the next couple of posts and Videos, that is exactly what we are going to cover extensively. Based on MDN, selectors can be categorized as follows:
- Simple selectors: These are simply based on the html element tags, a class or an id.
eg .homepage {/*Css styles*/} …. body {/*Css styles*/}
- Attribute selectors: Matches html elements based on their attributes values.
eg [attributes]{/*Css styles*/}… [attributes=”value”]{/*Css styles*/}
- Pseudo-classes: Matches an element based on its state or position on the page. Eg Based on state we can say, when hovered. And based on position we can say , the nth element such as the first-child, last-child and so on. More on MDN
Eg : a:hover{/*Css styles*/}… li:first-child{/*Css styles*/}
- Pseudo-elements: Matches based on an element’s position in relation to other elements on that page eg First word in a paragraph
Eg : ul::after{/*Css styles*/} … p::first-letter{/*Css styles*/}
- Combinators: These are used for digging deeper in order to target very specific elements on the page. For instance you may combine paragraph and a specific class in order to only target paragraphs which are in that class.
Eg : .homepage div p {/*Css styles*/}
- Multiple selectors: This will enable you to use the same CSS rules to affect the style of more than one selector. For example you may use the same style for paragraphs, headings and other items. This is doable by separating selectors using a comma
eg Eg : .Homepage div p ,.homepage p, h1,h2, h3 {/*Css styles*/}
Examples of CSS with selectors:
#1 : Styling a html element, body
body { background-color:white; color:black;max-width:1200px;}
#2 : Styling an html element by selecting its Identity (id), eg where id name is , homepage
When using an ID to style an element you must add this # at the beginning of the identity name as follows:
#homepage { background-color: grey; color: black; max-width:960px;}
#3 : Styling an html element by selecting its class,eg where the class is homepage
When using the class as the selector, you must add a dot (.) in front of the class name as follows
.homepage { background-color: grey; color: black; max-width:960px;}
If any of the above is confusing for you, ensure you watch the Video above, because it will help you understand this concept much better.
We’ll continue in the next post/video.
To learn more about HTML and CSS click the button below.
Discover more from Bizanosa
Subscribe to get the latest posts sent to your email.