CSS Selectors (Basic, Combinators, Attribute)
Selectors are the targeting system of CSS. Mastering them lets you style any element on the page with surgical precision.
What is it?
CSS selectors define which HTML elements on the page the style rules will apply to. They range from simple element names to complex combinators and attribute filters.
Why is it used?
Using precise selectors keeps your HTML clean and saves you from having to attach redundant classes to every single nested element.
Detailed Explanation
Syntax Structure
/* Element */ tag { ... }
/* Class */ .class-name { ... }
/* ID */ #id-name { ... }
/* Child */ parent > child { ... }
/* Attribute */ [attribute="value"] { ... }
Code Example
/* Universal box-sizing reset */
*, *::before, *::after {
box-sizing: border-box;
}
/* Class selector */
.tutorial-container {
max-width: 1200px;
margin: 0 auto;
}
/* Child combinator: only direct children */
.nav-list > li {
display: inline-block;
margin-right: 16px;
}
/* Adjacent sibling: first paragraph after an H2 */
h2 + p {
font-size: 18px;
color: #5f5f5d;
}
/* Attribute selector */
input[type="text"]:focus {
border-color: #1c1c1c;
outline: none;
}
Explanation of the Code
Expected Output
Real-World Application
Design systems like Bootstrap and Tailwind use attribute and combinator selectors to style complex component hierarchies.
Common Mistakes to Avoid
Quick Practice Challenge
Write a selector that targets only external links (href starting with 'https://') and gives them an underline and bold font.