Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

React
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
  • How a Web Page Works: HTML Tags, Elements and Attributes
  • Semantic HTML: header, nav, main, aside and footer as Page Landmarks
  • HTML Forms: Labels, Names, Input Types and Where the Data Goes (GET vs POST)
  • CSS Basics: Selectors, Which Rule Wins, and the Box Model
  • CSS Flexbox vs Grid: A Nav Bar, a Card Row and a Dashboard
  • Responsive CSS: Viewport, Mobile-First Media Queries, clamp() and Dark Mode with Tokens
  • JavaScript for People Who Already Code: Syntax, Modules and Five Surprises
  • JavaScript Arrays the Functional Way: map, filter, reduce, find, sort and Object.entries
  • Async JavaScript: Promises, async/await, fetch and Promise.all
  • JavaScript in the Page: the DOM, querySelector and Events
  • npm, package.json and Vite: What npm install Fetches and How Vite Serves and Builds Your Page
  • TypeScript Essentials: Types Checked, Then Erased (Interfaces, Unions, Generics)
  • Why React, JSX and Components: The Page as a Function of Data
  • React Props and Composition: Data Down, Calls Up, Children in the Slot
  • Routing With React Router: One Page, Many Addresses
  • React Component Tests With Vitest and Testing Library: Test What the User Sees
  • End-to-End Tests for a React App With Playwright: A Full Dress Rehearsal
  • Why AI-Built Websites All Look the Same, and Four Levels That Fix It
  • Visual Hierarchy, Spacing and the 8-Point Grid: Tell the Eye What to Read First
  • Colour, Contrast and Dark Palettes: 60-30-10, Semantic Tokens and Ratios You Can Compute
  • Typography That Sells: Type Scale, Line Length and Free Font Pairings
  • The UI Element Catalogue: Buttons to Toasts, Their Jobs, States and shadcn/ui Names
  • Design Tokens: Primitive and Semantic Tokens, from Figma to CSS to Tailwind
  • Tailwind CSS 4 in React: Utility Classes, Responsive Prefixes, Hover and Dark Mode
  • shadcn/ui in React: Components You Own, Edit and Commit
  • Design Tokens to a Tailwind Theme: Light and Dark Mode with @theme inline
  • Motion in React: Entrance, Hover, Exit and Layout Animations
  • A React Dashboard: Stat Cards, a Recharts Line Chart and a Sortable Table
  • Accessibility in Practice: Dialogs, Menus and the Keyboard in React
  • Reference-Driven Design: Extract a DESIGN.md From a Site You Admire and Build From It
  • Components, Variants and Variables: One Design System in Figma and in CSS
  • Figma MCP Server: Build a React Component From a Frame, Then Write It Back
  • Claude Design: From a Brief to a Clickable Prototype, Then Hand It Off to Claude Code
  • Critiquing AI-Generated UI: Six Checks for Every Screen
  • The AI Design Landscape: Prompt to UI, Prompt to App, and Design to Code
  • Your Brand Rules Folder: One Folder Every AI-Built Page Follows
  • The Best-Practice UI Prompt: Plain Sentences That Beat the Average AI Page
  • UI Ideas From Figma Make, Google Stitch and ChatGPT: One Prompt, Three Designs
  • Google Stitch From a Sketch or Screenshot: Show the Layout, Say What to Keep
  • Stitch to Figma to Code: Turn a Stitch Screen Into Code That Uses Your Tokens
  • Figma Make: Prompt to Prototype With a Four-Part Prompt
  • Upgrade a Dated UI From One Screenshot (or a Reference Image)
  • States and Feedback: Make Every Click Get an Answer
  • A Design-Loop Skill: Claude Screenshots, Scores and Fixes Its Own UI
  • Copy Without the AI Tells: A Copy Pass on a Landing Page
  • React State, Events, Lists and Conditional Rendering: Follow One Click
  • React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
  • Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
  • Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
  • React Context and Custom Hooks: Share One Value, Reuse the Logic
  • Server State With TanStack Query: One Key, One Request, One Cache
  • Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
  • Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
  • A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Forms With React Hook Form and Zod: The API's Rules in the Browser, the Server's Errors Under the Field
  • JWT Auth in a React Client With a FastAPI Backend: Log In, Carry the Token, Let the Server Decide
  1. Blog
  2. /
  3. React
  4. /
  5. Fundamentals

CSS Basics: Selectors, Which Rule Wins, and the Box Model

HTML says what each piece is, CSS says how it looks. Learn the parts of a rule, five selectors, why an id rule beats a class rule, and how padding, border and margin add up to 348px unless you use border-box.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Fundamentals

What you will learn

  • Read a CSS rule: selector, property, value, declaration
  • Pick elements with tag, class, id, descendant and :hover selectors
  • Predict which rule wins: id beats class, class beats tag, later wins a tie
  • Work out an element's width with padding, border, margin and box-sizing

Before you start

  • HTML tags, elements and attributes

Take a plain HTML page and add one file, style.css. The heading turns blue, the links turn green, the notes get a yellow background, and not one HTML tag changed. HTML says what each piece is. CSS says how it looks.

Three places to write CSS

  • Inline, a style attribute on one tag. It styles only that tag.
  • A <style> tag in the head. It styles only this page.
  • A linked file, <link rel="stylesheet" href="style.css">. Every page that links it gets the same look. This is the one you'll use most.

The parts of a CSS rule

The rule h1 { color: #1E40AF; } split into selector h1, property color, value #1E40AF, and the whole property: value; pair as one declaration. h1 { color : #1E40AF ; } selector property value one declaration (one setting) which tags? what to change? to what?
A selector picks the tags; each declaration inside the braces is property, colon, value, semicolon.

Values come in a few kinds you'll see all the time. A colour like #1E40AF is three pairs of hex digits for red, green and blue; simple names like red or white work too. A size in px is screen pixels, and rem means "times the normal text size": normal text is 16px, so 2rem is 32px. A font like Arial, sans-serif means "use Arial, and if it isn't installed, any plain sans-serif font".

Five selectors on one page

Here's the HTML:

  <h1>Web Basics</h1>
  <nav>
    <a href="#tasks">Tasks</a>
    <a href="#students">Students</a>
  </nav>
  <p class="note">Week 1: three small tasks.</p>
  <p>Ask <a href="#emma">Emma Clarke</a> if you get stuck.</p>
  <p class="note" id="deadline">Deadline: Friday.</p>

And the stylesheet:

/* tag: every <body> and every <h1> */
body { font-family: Arial, sans-serif; }
h1 { color: #1E40AF; font-size: 2rem; }

/* class: every tag with class="note" */
.note { background: #FEF3C7; padding: 8px; }

/* id: the one tag with id="deadline" */
#deadline { border-left: 6px solid #B91C1C; }

/* descendant: only an <a> inside <nav> */
nav a { color: #047857; margin-right: 16px; }

/* :hover - only while the mouse is on it */
nav a:hover { color: #B91C1C; }
  • h1 is a tag selector. It picks every h1; here there's one, so the heading turns blue.
  • .note is a class selector. The dot means class. Both paragraphs with class="note", the week 1 note and the deadline, turn yellow.
  • #deadline is an id selector. The hash means id, and it picks exactly one tag, which gets a red line on the left.
  • nav a is a descendant selector. The space means "inside", so only Tasks and Students turn green. The "Emma Clarke" link is also an a, but it's not inside nav, so it keeps the browser's normal blue.
  • nav a:hover adds a state. The colon rule applies only while the mouse is on the link, so the link under the mouse turns red and goes back to green when you move away. No JavaScript needed.

Which rule wins?

Two rules can give one tag two different colours. Picture a classroom. The teacher says "everyone, grey": that's a tag rule, and every student turns grey. Then "group B, green": that's a class, more exact, so group B turns green. Then "Emma Clarke, red": that's an id, called by name, the most exact of all. Emma heard all three, but she follows her own name.

So an id beats a class, and a class beats a tag. If two rules are equally exact, the one written later wins. This ranking is called specificity.

  <h1 id="welcome" class="title">Web Basics</h1>
  <p class="title">Week 1 starts on Monday.</p>
/* two rules aim at the same heading */
h1 {
  color: #6B7280;   /* tag rule: grey */
}
.title {
  color: #047857;   /* class rule: green - a class beats a tag */
}
/* BREAK IT: remove the comment marks around the id rule below.
   An id beats a class, so the heading turns red and the .title
   colour is crossed out in DevTools (Styles tab). */
/* #welcome { color: #B91C1C; } */

As written, h1 says grey and .title says green, and the class wins: the heading is green. Now remove the comment marks around #welcome. The heading turns red, with no error anywhere. Press F12 and the Styles tab in DevTools shows why: the .title colour is crossed out. It's still there; it just lost. The paragraph has no id, so it stays green.

When a style "doesn't work", this is the first place to look. The rule is usually fine and a more exact rule is beating it.

Every element is a framed picture

The other big idea in CSS is space. Every element is like a framed picture on a wall. The picture in the middle is the content. The mat around it is the padding. Then comes the frame, the border. And the wall up to the next picture is the margin. Padding is inside the frame; margin is outside.

/* width now includes padding and border */
* { box-sizing: border-box; }

body { font-family: Arial, sans-serif; }

.card {
  width: 300px;
  padding: 20px;               /* space inside the frame */
  border: 4px solid #1E40AF;   /* the frame itself */
  margin: 24px;                /* space outside, on the wall */
  background: #EFF6FF;
}

The HTML is two task cards, each a div with class="card". In DevTools the layers show in colour: the content is 252 by 102 pixels, the padding is 20px on every side, the border is 4px and the margin is 24px, the wall between the two cards. The light blue background fills the padding too, but the margin stays empty, because it's the wall, not the picture.

The width you write, or more?

Default content-box: 20 plus 4 plus 300 plus 4 plus 20 equals 348 pixels wide. With border-box the whole card is 300 pixels and the content shrinks to 252. content-box (the default): width = content only content 300 20 + 4 + 300 + 4 + 20 = 348px wide 300px line border-box: width = frame to frame content 252 padding and border fit inside = 300px wide green = padding, dark = border, blue = content (margin sits outside both)
The same width: 300px card with and without box-sizing: border-box.

By default, width means only the picture. Padding and border are added on top: 20 + 4 + 300 + 4 + 20 = 348 pixels, so the frame runs past the 300 line. With box-sizing: border-box, the padding and border fit inside. The card is 300 pixels frame to frame, and the content shrinks to 252.

That's why line 2 of the file is * { box-sizing: border-box; }. Put it at the top of every stylesheet and the width you write is the width you get.

Common mistakes

  • A class rule that "does nothing". An id rule or a later rule is beating it. Check the crossed-out lines in the DevTools Styles tab.
  • Forgetting the dot or hash. note { } looks for a <note> tag, which doesn't exist.
  • Mixing up padding and margin. Background colour fills the padding, never the margin.
  • Boxes wider than you set. Add box-sizing: border-box.

Quick recap

SelectorPicksStrength
h1every tag of that kindweakest
.noteevery tag with that classbeats a tag
#deadlinethe one tag with that idbeats a class
nav aan a inside a navadds up its parts
nav a:hoverthe same, only while hovereda state

Try it yourself

In the box model example, give the first card a class and an id, colour it with both, and predict which one wins before you reload. Then open DevTools, change the padding, border and margin live, and watch the coloured layers move. Next up: putting boxes side by side with Flexbox and Grid.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in React · 6 of 59

Previous
HTML Forms: Labels, Names, Input Types and Where the Data Goes (GET vs POST)
Next post
CSS Flexbox vs Grid: A Nav Bar, a Card Row and a Dashboard

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

One Request, Two Answers: the Same Post as an HTML Page and as JSON

Ask a Django blog for the same post twice: once as a 12,731-byte HTML page built by a template, once as 2,976 bytes of JSON built by a serializer. Compare the headers, see who builds the page, and why the server still owns every write.

A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx

Make a blog design from a prompt in Figma Make, download src.zip, unzip it with Python's zipfile module, and read the two files that matter: App.tsx with its selectedPost state and BlogCard.tsx with its props.

How a Web Page Works: HTML Tags, Elements and Attributes

A web page is a text file full of labelled pieces. Learn tags, attributes and nesting with three tiny pages, and see what breaks when an attribute or a closing tag is wrong.

Semantic HTML: header, nav, main, aside and footer as Page Landmarks

The same page written as div soup and with semantic tags looks identical, but only one gives screen readers and search engines landmarks and an outline. Plus tables, div, span and the one-main rule.

On this page

  • Three places to write CSS
  • The parts of a CSS rule
  • Five selectors on one page
  • Which rule wins?
  • Every element is a framed picture
  • The width you write, or more?
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.