CSS Selectors Explained with Code Examples
1. Universal Selector (*)
Selects all elements.
<style>
*{
margin: 0;
padding: 0;
}
</style>
2. Element Selector (p, h1, etc.)
Targets elements by tag name.
<style>
p{
color: blue;
font-size: 16px;
}
</style>
<p>This is a paragraph.</p>
3. Class Selector (.classname)
Selects elements with a specific class.
<style>
.highlight {
background-color: yellow;
}
</style>
<p class="highlight">This text is highlighted.</p>
4. ID Selector (#id)
Selects an element with a unique ID.
<style>
#main-title {
color: green;
font-size: 24px;
}
</style>
<h1 id="main-title">Welcome to My Page</h1>
5. Grouping Selector (p, h1, h2)
Applies styles to multiple elements.
<style>
h1, h2, p {
font-family: Arial;
}
</style>
6. Descendant Selector (div p)
Targets <p> inside <div>.
<style>
div p {
color: purple;
}
</style>
<div>
<p>This paragraph is inside a div.</p>
</div>
7. Child Selector (ul > li)
Selects direct children only.
<style>
ul > li {
list-style-type: square;
}
</style>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
8. Attribute Selector
Target elements with specific attributes.
<style>
input[type="text"] {
border: 2px solid blue;
}
</style>
<input type="text" placeholder="Enter name">
<input type="password" placeholder="Enter password">
9. Pseudo-class (:hover, :first-child, etc.)
<style>
a:hover {
color: red;
text-decoration: underline;
}
li:first-child {
font-weight: bold;
}
</style>
<a href="#">Hover over this link</a>
<ul>
<li>First item</li>
<li>Second item</li>
</ul>
10. Pseudo-element (::before, ::after)
<style>
p::before {
content: "Note: ";
font-weight: bold;
color: red;
}
</style>
<p>This is an important message.</p>