CSS Selectors : The Art of Precision

Imagine you are in a party and you need to talk to any person how would you say that. Can you shout like “Hey human!” ? Probably Not, because it does not specify any particular person, it points to everyone in the room. Either you could say that “Hey black shirt man! ”, this is may still not work because it can point to many persons wearing black shirt. The best way would be “Hey Jhon Deo!” that’s points to a particular person.
Similarly in web development the CSS Selectors are how you address your page. We use them to select a particular element and design it better to showcase the HTML tags in display in better way.
Why CSS selectors are needed?
HTML provides the structure or the skeleton of the website, but CSS make the skin and cloths or the design for the website. Without the selector CSS is just a list of styles with no where to go. They are like the bridge between the content and the design. The more specific your selector, the more targeted your styling becomes. Here are some CSS selectors with example.
Element selector
The most basic way to style a HTML tag name. It target all the elements of a specific HTML tag.
/* All paragraphs will have red text */
p {
color: red;
}
Before plane black text for every <p> tag, after every paragraph have a red colour.
Class selector
The classes are the most versatile and common selector. A class selector target elements with a specific class name. Classes are defined using the class attribute in HTML and selected using a dot (.) in CSS.
<h2 class="highlight">Hello World!</h2>
<p class="highlight">How are you?</p>
.highlight {
background-color: yellow;
font-weight: bold;
}
Only the elements with class="highlight" have a yellow background.
ID selector
The ID selectors use the unique names for a specific element. A ID selector target elements with a specific ID. IDs are defined using the id attribute and selected using a hash (#) in CSS.
<h1 id="main-title">Welcome</h1>
#main-title {
color: red;
}
The main-title id becomes colour red.
Group selectors
If you want multiple different element should share the same design or style then you need to group them using a comma(,).
h1, h2, p {
text-align: center;
}
All h1, h2 and p tags text are aligned in centre.
Descendant selectors
Sometimes you only want to style an element if it sits inside any other specific element.
/* Only style spans that are inside a footer */
footer span {
font-size: 12px;
color: grey;
}
Basic selector priority
What happens when you tell all paragraph to be blue, but you tell a specific paragraph class to be Red? It will be blue or red?
In this scenario, CSS follows a rule called Specificity. Cascading an element does not depends on line number, it depends on the priority and specificity. In a very high level the ID has more priority then the class and at last the element or tag name.




