Master advanced selector techniques for precise element targeting
CSS selectors are patterns used to select and style HTML elements. Understanding ID selectors, class selectors, grouping, and nesting gives you precise control over your webpage styling.
The class selector targets elements with a specific class attribute. Classes can be used on multiple elements and are reusable.
.classname {
property: value;
}
<p class="highlight">This is highlighted text.</p>
<div class="highlight">This div is also highlighted.</div>
.highlight {
background-color: yellow;
padding: 10px;
border-radius: 5px;
}
Key Points:
The ID selector targets a unique element with a specific ID attribute. IDs should be unique within a page.
#idname {
property: value;
}
<div id="header">
<h1>Welcome to My Website</h1>
</div>
#header {
background-color: #667eea;
color: white;
padding: 20px;
text-align: center;
}
Key Points:
Group multiple selectors together to apply the same styles, reducing code repetition.
selector1, selector2, selector3 {
property: value;
}
h1, h2, h3 {
font-family: Arial, sans-serif;
color: #333;
}
.btn-primary, .btn-secondary, .btn-danger {
padding: 10px 20px;
border-radius: 5px;
border: none;
cursor: pointer;
}
Benefits:
Nesting selectors target elements based on their parent-child relationship in the HTML structure.
parent child {
property: value;
}
<div class="container">
<p>This paragraph is inside container.</p>
<div class="inner">
<p>This paragraph is inside inner div.</p>
</div>
</div>
.container p {
color: blue;
}
.container .inner p {
color: red;
font-weight: bold;
}
Nesting Types:
div p (any p inside div)div > p (direct child only)h2 + p (p immediately after h2)h2 ~ p (all p siblings after h2)Elements can have multiple classes, allowing you to combine different styles.
<button class="btn btn-large btn-primary">
Click Me
</button>
.btn {
padding: 10px 20px;
border: none;
cursor: pointer;
}
.btn-large {
font-size: 18px;
padding: 15px 30px;
}
.btn-primary {
background-color: #667eea;
color: white;
}
This paragraph uses class (.demo-highlight)
This paragraph also uses the same class
Q1: Which symbol is used for class selectors in CSS?
Q2: Can multiple HTML elements have the same ID?
Q3: What does the selector "div p" target?
Q4: How do you select an element with id="main" in CSS?
Q5: What is the purpose of grouping selectors (h1, h2, h3)?
h1, h2, h3)parent child)