CSS Basics
CSS â Cascading Style Sheets â is a rule language that turns an HTML tree into something you can see. A rule pairs a selector, which targets elements, with a block of declarations, each a property and a value. What makes CSS tricky is not the syntax; it is the cascade: when several rules could apply, a deterministic algorithm picks one. Understanding that algorithm is the difference between styles that behave predictably and styles you fight for hours.
By the end of this lesson you will be able to write selectors that hit exactly the elements you mean, explain why one rule beats another, reason about spacing with the box model, and keep stylesheets maintainable as a project grows.
Anatomy of a Rule and Where It Lives
Styles can arrive from three places: the browser's default stylesheet, author styles written by you, and user styles set by the reader (rare, but real â think enlarged default fonts). Author styles always beat browser defaults, and media-query rules declared later override earlier ones of equal weight.
/* A single rule: selector, declarations, property, value */
.card {
padding: 1.5rem;
border: 1px solid #e2e8f0;
border-radius: 12px;
}
.card h2 {
margin: 0 0 0.5rem;
font-size: 1.25rem;
}
.card--featured {
border-color: #2563eb;
box-shadow: 0 4px 14px rgb(37 99 235 / 0.2);
}
You can attach CSS to a page with a link element in the head, an @import inside another stylesheet (avoid it â it serializes loading), or an inline style attribute on a single element. Production sites use external files so browsers can cache them and so markup stays free of presentation.
Selectors: Matching Elements Precisely
Selectors range from dead simple to gloriously specific. The browser reads them right to left: in .card h2, it first finds every h2, then keeps only those whose ancestors include a .card element. That right-to-left evaluation is why deep selectors cost more than shallow ones.
| Selector | Matches | Specificity |
|---|---|---|
* | Every element | 0 |
p | All paragraph elements | 1 |
.card | Elements with class card | 1-0 |
#main | The element with id main | 1-0-0 |
.card h2 | h2 inside a card | 1-1 |
a:hover | Anchors while hovered | 2-1 |
li:nth-child(odd) | Odd list items | 2-1 |
input[type="email"] | Email inputs | 2-1 |
Attribute selectors like the email example are underused. They let you style form fields by type without adding classes to every input.
The Cascade: How the Winner Is Chosen
When several rules match the same element, the browser resolves them in four steps. First it compares origin and importance (user-agent, then author, with !important flipping the order within each). Then it compares specificity using the three-part a-b-c score: id counts, then classes/attribute selectors/pseudo-classes, then plain elements and pseudo-elements. Only if the scores tie does source order decide â the last matching declaration wins.
Inline style attributes sit above stylesheet rules of any specificity, which is why they are convenient in prototypes and painful in teams. Prefer classes. A cascade layer via @layer lets you declare a global order between groups of styles, so component CSS can never accidentally outrank your design tokens.
The Box Model Inside Out
Every element generates a box composed of content, padding, border, and margin. By default, the width property sizes the content box, so adding padding or a border makes the element physically wider â the classic cause of layouts that overflow their container by a few pixels.
/* Global reset trick: width now includes padding and border */
*,
*::before,
*::after {
box-sizing: border-box;
}
.demo {
width: 320px;
padding: 24px;
border: 4px solid #334155;
/* With border-box the visible box is exactly 320px wide */
}
Setting box-sizing: border-box on everything is the modern default in every CSS reset. Margins collapse between adjacent siblings â the larger of the two wins â while padding never collapses. Vertical rhythm in text layouts usually comes from giving paragraphs a bottom margin and letting collapse do the rest.
Colors, Units, and Typography Foundations
Modern CSS offers several color notations: hexadecimal like #2563eb, rgb() with alpha, and hsl(), which is far easier to tweak by hand because lightness and saturation are separate channels. For sizing, use relative units. rem scales with the root font size, making whole layouts respond to a user's preferred text size; em scales with the parent's font size, which is useful for padding inside text but confusing for layout widths. Reserve pixels for borders and cases where you genuinely want a fixed size.
For typography, set a readable base: a line height around 1.5 to 1.7 for body copy, a maximum line length near 70 characters, and margins rather than padding for vertical spacing between blocks.
Writing Rules That Stay Maintainable
Small stylesheets need no architecture; large ones die without it. Name classes by role or component (site-nav, price-tag) rather than appearance (blue-text, small-box), because appearance changes and roles rarely do. Keep selectors shallow â one or two classes â so a later change in markup does not silently break distant rules. Put shared values such as colors, spacing steps, and font stacks into custom properties on :root, and reference them everywhere else; a single edit then restyles the whole product.
Combinators, Pseudo-Classes, and Modern Selectors
Selectors get expressive once combinators and pseudo-classes combine. The descendant combinator, written as a space, matches at any depth; the child combinator â a single greater-than sign â matches exactly one level, and the difference matters the moment a card contains another card. Adjacent-sibling and general-sibling combinators reach elements that follow their reference, which is how stacked form rows and label-after-input patterns get styled without extra wrappers.
Pseudo-classes describe state or position without extra markup in the HTML. :hover covers the pointer, :focus-visible covers keyboard-driven focus so mouse users are not punished with outlines on click, and :focus-within styles a whole form whenever any field inside it holds focus. :nth-child(odd) zebra-stripes table rows; :last-child tightens spacing at the end of a stack; :not(.is-hidden) filters elements without nesting conditions.
The relative newcomer, :has(), is often called the parent selector because it finally lets a container react to its descendants. A form styled with :has(:invalid) can highlight its entire border while any field is failing, and a card can grow a badge when it contains an image â all without a single line of JavaScript. Browser support is now broad enough for production, with the fallback rule listed first for stragglers.
Chaining affects specificity: a hover state on a classed anchor counts one type plus one class plus one pseudo-class, so it reliably outranks a bare class rule. That power is also a warning â each added simple selector makes future overrides harder. When a selector needs combinators three levels deep, the sturdier fix is usually adding a class to the element you actually want to style. Short selectors document themselves; long ones become archaeology.
Best Practices
- Set box-sizing: border-box globally before writing any layout CSS.
- Prefer class selectors over id selectors â ids carry 1-0-0 specificity and cannot be reused.
- Define colors, spacing, and fonts once as custom properties on :root.
- Use rem for font sizes and spacing so users who enlarge text are respected.
- Keep selector specificity low; reach for cascade layers instead of !important.
- External stylesheets over inline style attributes, always, in real projects.
Key Takeaways
- The cascade picks a winner by origin and importance, then specificity, then source order.
- Specificity is a three-part score: ids beat classes and attribute selectors, which beat element names.
- box-sizing: border-box makes width include padding and border, preventing overflow surprises.
- rem scales with the root font size; em scales with the parent â choose deliberately.
- Custom properties turn scattered magic values into one editable source of truth.
- Shallow, role-based class names keep stylesheets predictable as teams grow.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type â Always start by categorizing the problem
- Incorrect formula application â Verify the formula applies to your specific case
- Unit errors â Always check units are consistent throughout
- Sign errors â Pay careful attention to positive and negative values
- Rounding too early â Keep full precision until the final answer
- Forgetting constraints â Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic â Build on the foundation laid here
- Next Topic â See how this concept extends to more advanced material
- Practice Problems â Additional exercises with solutions
- Video Explanation â Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions