Hello to everyone I know selecting the right selector for an element is little bit tricky . But believe me once you understand the concept , it's like a piece of cake for you .
Just keep in your mind , it is a journey not a one day workshop . So as much as you dig into it the more you get from it . So lets start your journey from this moment .
So what is Selector and how it affect the style of a web page
Basically selector is a name which is given by us or it is predefined (as a HTML Tag) in the html file .Now by using this name we target the particular element for styling our webpage .
Now Css Provide us different type of selector and some of them are :
ID selector
ID selectors are the most powerful type of selector . That sounds good, but that’s typically considered bad, because it’s nice to have lower-specificity selectors that are easier to override when needed.
HTML
<!-- WILL match -->
<div id="happy-cake"></div>
<!-- Will NOT match -->
<div id="sad-cake">Wrong ID!</div>
CSS
#happy-cake {
}
Class Selector
It is most useful and versatile selectors . They are well supported in all browsers. You can add multiple classes (just separated by a space) on HTML elements.
HTML
<!-- WILL match -->
<div class="module"></div>
CSS
.module {
}
Tag selectors
They are most useful when changing properties that are unique to that HTML element . HTML
<h2>Hi, Mom</h2>
CSS
h2 {
}
Attribute Selector
HTML
<aside class='closed' data-modal='open'></aside>
CSS
[data-modal="open"] {
}
Positional Selectors
There are different type of positional selectors are available here we use one of them just to show how it works .
HTML
<ul>
<li>nope</li>
<!-- WILL match -->
<li>yep, I'm #2</li>
<li>nope</li>
</ul>
CSS
:nth-child(2) {
}
Other Pseudo Selectors
:empty is one of many pseudo selectors, which you can recognize by the colon (:) in them. They typically represent something that you couldn’t know by just the element and attributes alone.
HTML
<!-- WILL match -->
<div></div>
<!-- WILL match -->
<aside data-blah><!-- nothin' --></aside>
<!-- Will NOT match -->
<div> </div>
<!-- Will NOT match -->
<div>
</div>
CSS
:empty {
}
Combined Selectors
CSS
.module > h2 {
/* Select h2 elements that are direct children of an element with that class */
}
h2 + p {
/* Select p elements that are directly following an h2 element */
}
li ~ li {
/* Select li elements that are siblings (and following) another li element. */
}
.module.news {
/* Selects elements with BOTH of those classes */
}
#site-footer::after {
/* Adds content after an element with that ID */
}
section[data-open] {
/* Selects only section elements if they have this attribute */
}
There are some other types of selectors are also available , You can refer MDN docs for depth knowledge .
Thanks for reading .