You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
CSS selectors are patterns that match HTML elements. Choosing the right selector is key to writing CSS that is precise, maintainable, and easy to override.
/* Type selector — targets all elements of that type */
p { color: #333; }
/* Class selector — targets elements with class="highlight" */
.highlight { background-color: yellow; }
/* ID selector — targets the element with id="main-title" */
#main-title { font-size: 2.5rem; }
/* Universal selector — targets every element */
* { box-sizing: border-box; }
Classes are the most common selector in real-world CSS. IDs are highly specific and should be used sparingly. The universal selector is mostly used for CSS resets.
Combinators let you select elements based on their relationship to other elements:
/* Descendant — any p inside .container */
.container p { margin: 0; }
/* Child — direct children only */
.container > p { font-weight: bold; }
/* Adjacent sibling — h2 immediately followed by p */
h2 + p { font-size: 1.1rem; }
/* General sibling — all p elements after h2 */
h2 ~ p { color: #666; }
Pseudo-classes match elements based on their state or position:
a:hover { color: blue; text-decoration: underline; }
a:visited { color: purple; }
input:focus { outline: 2px solid blue; }
li:first-child { font-weight: bold; }
li:last-child { border-bottom: none; }
li:nth-child(odd) { background: #f9f9f9; }
Pseudo-elements target parts of an element rather than the whole element:
p::first-line { font-weight: bold; }
p::first-letter { font-size: 2em; float: left; }
.quote::before { content: "“"; }
.quote::after { content: "”"; }
body {
font-family: "Inter", sans-serif;
font-size: 16px;
font-weight: 400;
line-height: 1.6;
color: #222;
letter-spacing: 0.01em;
}
.card {
color: #333; /* named, hex */
background-color: rgb(255, 255, 255); /* rgb */
background-color: hsl(210, 100%, 56%); /* hsl */
background-image: url("bg.png");
background-size: cover;
background-position: center;
}
.box {
border: 1px solid #ddd;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
When multiple rules target the same element, the browser calculates a specificity score:
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.