Introduction
CSS selectors are the backbone of styling in web development. They allow you to target HTML elements and apply styles efficiently.
Whether you're a beginner or an experienced developer, mastering selectors will make your CSS cleaner, faster, and more powerful.
1. Basic CSS Selectors
HTML Syntax
<p>This is a paragraph</p>
CSS
p{
color: #596af7;
}
Class Selector
Targets elements with a specific class.
HTML Syntax
<p class="text">Hello World</p>
CSS
.text{
color: #596af7;
}
ID Selector
Targets a unique element.
HTML Syntax
<p id="title">Welcome</p>
css
#title{
color: #596af7;
}
2. Grouping Selector
Apply same styles to multiple elements.
HTML Syntax
<p>Selectors are powerful!</p>
<h1>Title heading</h1>
<span>Sub heading</span>
CSS
p,h1,span{
color: aquamarine;
}
3. Descendant Selector
Targets elements inside another element.
HTML Syntax
<div>
<p>Inside div</p>
</div>
CSS
div p{
color: palegreen;
}
4. Child Selector (>)
Targets direct children only.
CSS
div > p{
color: aqua;
}
5. Attribute Selector
Targets elements based on attributes.
HTML Syntax
<input type="text" />
<input type="password" />
CSS
input[type="text"] {
border: 2px solid blue;
}
6. Pseudo-Class Selectors
Used for specific states.
Hover Example
HTML Syntax
<button>Submit</button>
CSS
button:hover {
background-color: black;
color: white;
}
First Child
li:first-child {
color: red;
}
7. Pseudo-Element Selectors
First letter
CSS
p::first-letter {
font-size: 24px;
color: #596af7;
}
Before Element
CSS
p::before {
content: "";
}
8. Universal Selector
Targets all elements.
CSS
* {
margin: 0;
padding: 0;
}
9. Adjacent Sibling Selector (+)
Targets immediate next element.
CSS Syntax
h1 + p {
color: green;
}
10. General Sibling Selector (~)
Targets all siblings.
CSS
h1 ~ p {
color: gray;
}
Real-Time Example (Mini Project)
HTML Syntax
<div class="card">
<h2>CSS Selectors</h2>
<p>Selectors are powerful!</p>
</div>
CSS
.card {
border: 1px solid #ccc;
padding: 15px;
margin: 10px 0px;
}
.card:hover {
background-color: #f5f5f5;
}
.card h2 {
color: #596af7;
}
.card p::first-letter {
font-size: 18px;
font-weight: 500;
}
input[type="text"] {
border: 2px solid lightblue;
}
Conclusion
CSS selectors are essential for writing efficient and scalable styles. Once you master them, you can build complex layouts with minimal code.
Top comments (0)