When styling a webpage, you need to know CSS and understand how to use the right selectors to achieve your desired result. Selectors help you target specific HTML elements to apply styles efficiently.
1. Universal Selector (*
)
The universal selector applies styles to all elements on the page.
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
Use it sparingly, mainly for resetting default styles.
2. Element Selector (element
)
The element selector targets all instances of a specific HTML tag.
p {
color: blue;
font-size: 16px;
}
You can use this for general styling of common elements (e.g., body
, h1
, p
).
3. Class Selector (.class
)
The class selector targets elements with a specific class.
.highlight {
background-color: yellow;
font-weight: bold;
}
<p class="highlight">This text is highlighted.</p>
Best for reusable styles across multiple elements.
4. ID Selector (#id
)
The ID selector targets an element with a specific id
.
#header {
background-color: navy;
color: white;
padding: 10px;
}
<div id="header">Welcome to My Website</div>
Use for 'one-off' styles only.
5. Grouping Selector (A, B, C
)
This allows styling multiple elements at once.
h1, h2, h3 {
font-family: Arial, sans-serif;
color: darkslategray;
}
It helps to avoid redundant styles and keep CSS clean.
6. Descendant Selector (A B
)
Targets elements inside a specific parent.
nav ul {
list-style-type: none;
padding: 0;
}
<nav>
<ul>
<li>Home</li>
<li>About</li>
</ul>
</nav>
They Keep selectors short and readable.
7. Child Selector (A > B
)
Targets direct children only.
div > p {
color: red;
}
<div>
<p>Styled paragraph</p> <!-- Affected -->
<section>
<p>Not affected</p> <!-- Not affected -->
</section>
</div>
Use when only direct children need styling.
8. Adjacent Sibling Selector (A + B
)
Targets an element immediately after another.
h1 + p {
color: green;
}
<h1>Heading</h1>
<p>This paragraph is green.</p>
<p>This one is not.</p>
Use for styling elements right after another.
9. General Sibling Selector (A ~ B
)
Targets all matching siblings after a specific element.
h1 ~ p {
color: orange;
}
<h1>Heading</h1>
<p>This is orange.</p>
<p>This is also orange.</p>
Use when multiple elements after a specific one need styling.
Conclusion
Mastering selectors makes styling easier and more structured! 🚀
What do you normally use when styling?
I'm a full stack JS/TS developer open to collaboration and job offers. Feel free to reach out to me
Top comments (0)