Selectors, box model in React JS
Course: React JS Training
Topic: Selectors, box model
Course Link: React JS Training
Demo Link: Register for a Course Demo
1. Why Selectors and the Box Model Matter
Every piece of CSS you will ever write answers two questions. The first question is which element am I talking to? — that is the job of a selector. The second question is how much space does that element take on the page? — that is the job of the box model. Together they form the foundation of all styling on the web, from a simple personal page to a large React application.
This matters for your later modules too. When you build React components, those components finally render ordinary HTML elements in the browser, and you style them with the same selectors and the same box model you learn here. If this foundation is weak, layouts break in confusing ways later; if it is strong, Flexbox, Grid and media queries in the next pages become easy.
What you will be able to do after this page
- Pick the right selector for any element on a page.
- Combine selectors to target elements precisely, without adding extra classes everywhere.
- Predict which rule wins when two rules style the same element.
- Calculate the real width and height of any box, and control it with
box-sizing.
2. What Is a Selector?
In simple words: a selector is the part of a CSS rule that tells the browser which HTML elements the styles should be applied to. Think of it like writing an address on an envelope. The selector is the address — it finds the recipient. Everything after it is the message — the styles to deliver.
p {
color: darkgreen;
}
Here p is the selector. It says: find every <p> element on the page and make its text dark green. Every other element, such as headings or buttons, is untouched.
A selector can be very simple (just a tag name) or very precise (an element with a certain class, inside a certain section, in a certain state such as being hovered). The rest of this page walks up that ladder from simple to precise.
3. Key Terms You Will See Everywhere
Before writing rules, make sure these words feel familiar. CSS documentation and interview discussions use them constantly.
| Term | Meaning in plain words |
| Rule (rule set) | One complete block of CSS: a selector plus its declarations. |
| Selector | The part before the braces that chooses which elements get the styles. |
| Declaration | A single instruction such as color: red; — a property and a value. |
| Property | The thing you want to change, for example color or margin. |
| Value | The setting you give the property, for example red or 16px. |
| Declaration block | Everything between the { and } braces. |
| Specificity | The ranking system that decides which selector is "stronger" when rules conflict. |
| Cascade | The overall process browsers use to pick the winning rule when many rules match one element. |
4. Anatomy of a CSS Rule
Every CSS rule follows the same structure, so learn it once and you can read any stylesheet forever.
selector {
property: value;
property: value;
}
Broken down piece by piece:
- Selector — written first, outside the braces. It targets elements.
- Opening brace
{ — starts the declaration block.
- Declarations — each one is
property: value;, ending with a semicolon.
- Closing brace
} — ends the rule.
A complete, runnable example. Save it as index.html and open it in a browser:
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
color: navy;
font-size: 28px;
}
</style>
</head>
<body>
<h1>Welcome to CSS</h1>
<p>This paragraph is not styled by the rule above.</p>
</body>
</html>
The heading turns navy at 28 pixels; the paragraph stays default because the selector h1 only matches heading elements. Whitespace and line breaks inside a rule do not matter to the browser, but tidy indentation helps humans read the code.
5. Basic Selectors: Element, Class, ID, and Universal
These four selectors cover most everyday styling.
Element (type) selector
Matches every element of that type. Use it when you want a consistent default look for a tag.
/* every button on the page */
button {
font-size: 16px;
}
Class selector
Matches every element whose class attribute contains that name, written with a leading dot. Classes are reusable — many elements can share one class, and one element can carry several classes.
<p class="note">Remember to save your work.</p>
<div class="note">Notes can live on other tags too.</div>
.note {
background-color: lightyellow;
}
ID selector
Matches the single element with that id attribute, written with a leading hash. An id must be unique on the page.
<header id="top-bar">...</header>
#top-bar {
background-color: black;
}
Universal selector
The star * matches every element. It is mostly used in resets, as you will see later with box-sizing.
Quick comparison
| Selector | Syntax | Matches | Typical use |
| Element | p | All <p> elements | Default look for a tag |
| Class | .note | All elements with class="note" | Reusable styles, the everyday workhorse |
| ID | #top-bar | The one element with that id | Unique page landmarks |
| Universal | * | Every element | Resets and global settings |
6. Grouping and Combining Selectors
Grouping with commas
When several selectors should share the same styles, list them separated by commas instead of repeating the block three times.
h1,
h2,
h3 {
font-family: Georgia, serif;
}
Combining conditions on one element
Writing selectors together with no space between them means "all of these must be true for the same element". p.note matches a <p> that also has the class note. .btn.primary matches an element carrying both classes at once.
<button class="btn primary">Save</button>
<button class="btn">Cancel</button>
.btn {
padding: 8px 16px;
}
.btn.primary {
background-color: darkgreen;
color: white;
}
Only the Save button gets the green background, because only it has both classes. This pattern keeps CSS small: shared styles live in .btn, variations live in extra classes.
7. Combinators: Selecting by Relationship
HTML is a family tree: elements have parents, children and siblings. Combinators let a selector describe a relationship, not just a tag.
| Combinator | Syntax | Meaning |
| Descendant | A B (a space) | B anywhere inside A, at any depth |
| Child | A > B | B directly nested inside A |
| Adjacent sibling | A + B | B immediately after A |
| General sibling | A ~ B | B anywhere later, sharing the same parent |
A worked example you can run:
<nav class="menu">
<ul>
<li>Home</li>
<li>Courses</li>
</ul>
</nav>
<p>Outside the nav.</p>
/* any li inside .menu, at any depth */
.menu li {
list-style: none;
}
/* only ul elements whose direct parent is .menu */
.menu > ul {
margin: 0;
}
The space in .menu li means "any <li> at any nesting depth inside the nav". The > in .menu > ul means "only a <ul> whose direct parent is the nav" — if someone later wraps the list in another element, the child selector stops matching while the descendant selector keeps working. Choosing between them is a real decision: descendant selectors are flexible, child selectors are safer against unexpected nesting.
8. Pseudo-Classes: Selecting by State
A pseudo-class starts with a colon and matches an element in a particular state or position, without you adding any extra class in the HTML.
:hover — the mouse pointer is over the element.
:focus — the element is ready for keyboard input, for example a focused input field.
:first-child — the element is the first child of its parent.
:nth-child(2) — the second child of its parent; :nth-child(odd) and :nth-child(even) are common for striped tables.
<a href="#" class="link">Read more</a>
.link {
color: darkblue;
}
.link:hover {
color: crimson;
}
The link is dark blue normally and turns crimson only while hovered. No JavaScript is needed — the browser switches states for you. You will use :hover and :focus constantly in buttons, forms and navigation.
9. How the Browser Decides: Specificity and the Cascade
What happens when two rules both match the same element and both set color? The browser does not flip a coin. It follows three checks, in this order:
- Order: if two rules have equal strength, the later one wins.
- Specificity: the more precise selector wins, regardless of order.
- Inline styles: a
style attribute written directly on the element beats all of the above.
A practical way to think of specificity is a three-digit score written as ids – classes – elements:
- Element selector such as
p → 0–0–1.
- Class selector such as
.note → 0–1–0.
- ID selector such as
#top → 1–0–0.
p.note combines a class and an element → 0–1–1.
Compare scores from left to right; the first position that differs decides the winner.
/* score 0-0-1 */
p {
color: gray;
}
/* score 0-1-0 — this one wins */
.note {
color: darkred;
}
<p class="note">This text is dark red.</p>
Both rules match the same paragraph, but .note outranks p, so dark red wins even though the p rule is written later. A good habit from day one: style with classes and keep selector strength low. Fighting high-specificity selectors later is one of the most common sources of frustration in real projects.
10. What Is the Box Model?
In simple words: the box model is the rule that the browser renders every HTML element as a rectangle built of four layers. Whether it is a paragraph, an image or a button, the same structure wraps it, and every layout on the web is boxes inside boxes.
+--------------------------------------+
| margin |
| +------------------------------+ |
| | border | |
| | +----------------------+ | |
| | | padding | | |
| | | +--------------+ | | |
| | | | content | | | |
| | | +--------------+ | | |
| | +----------------------+ | |
| +------------------------------+ |
+--------------------------------------+
- Content — the actual text, image or nested elements.
- Padding — transparent space inside the box, between content and border. The element's background extends into it.
- Border — the line drawn around the padding.
- Margin — transparent space outside the border, pushing neighbours away. It never has a background.
A memory trick: padding is the bubble wrap inside a parcel, the border is the parcel's carton, and margin is the empty floor you keep around it so parcels never touch.
11. The Four Layers Step by Step
Content size with width and height
By default, width and height size the content area only — not the padding and not the border. Keep this in mind; it becomes important in a moment.
Padding — space inside
The padding property accepts one to four values, applied clockwise starting from the top:
.box {
padding: 20px; /* all four sides */
padding: 10px 20px; /* top and bottom, then left and right */
padding: 10px 20px 30px 40px; /* top, right, bottom, left */
}
Border — the line around
A border needs three ingredients, usually written in one shorthand: thickness, style and colour.
.box {
border: 2px solid gray;
}
Margin — space outside
Margin uses the same shorthand pattern as padding. One special value is auto: with a fixed width, left and right margins of auto center the box inside its parent. One quirk to know early: vertical margins of neighbouring block elements can collapse into each other, and the browser uses the larger margin rather than adding both.
.card {
width: 400px;
margin: 24px auto; /* 24px top and bottom, centered horizontally */
}
Calculating the real size
.box {
width: 200px;
padding: 20px;
border: 5px solid black;
}
With the default sizing, the visible box is 200 + 20 + 20 + 5 + 5 = 250px wide. The declared width covers only the content; padding and border are added on top of it. This surprises every beginner, and it is exactly the problem the next section solves.
12. box-sizing: content-box vs border-box
The box-sizing property changes what width actually means. There are two values you need to know:
| Value | What width includes | Effect |
content-box (default) | Only the content | Padding and border make the box grow bigger than the width you typed |
border-box | Content + padding + border | The box stays exactly that width; padding and border squeeze inward |
With border-box, the previous example becomes predictable: width: 200px means the whole visible box is 200px, because the browser shrinks the content area to make room for the padding and border.
Because border-box is far easier to reason about, almost every modern project applies it to every element through the universal selector:
* {
box-sizing: border-box;
}
Put this near the top of your stylesheet — many developers also include the ::before and ::after pseudo-elements in the same rule — and layout maths becomes simple everywhere on the page.
13. A Realistic Worked Example: A Profile Card
Everything on this page comes together in one small, realistic component — a card you could drop into any portfolio or dashboard.
<!DOCTYPE html>
<html>
<head>
<style>
* {
box-sizing: border-box;
}
.card {
width: 320px;
padding: 24px;
border: 1px solid lightgray;
border-radius: 8px;
margin: 40px auto;
font-family: Arial, sans-serif;
}
.card .name {
margin: 0 0 8px 0;
font-size: 20px;
color: navy;
}
.card p {
margin: 0 0 16px 0;
color: dimgray;
}
.card .btn {
display: block;
width: 100%;
padding: 10px;
border: none;
background-color: darkgreen;
color: white;
font-size: 16px;
}
.card .btn:hover {
background-color: seagreen;
}
</style>
</head>
<body>
<div class="card">
<h3 class="name">Asha Verma</h3>
<p>Frontend learner. Building small projects every week.</p>
<button class="btn">View profile</button>
</div>
</body>
</html>
Read the CSS against the ideas from this page:
* { box-sizing: border-box; } — every box on the page now measures width honestly.
.card — a class selector styles the container. Its real width is exactly 320px, because border-box counts the 24px padding and the 1px border inside that number. margin: 40px auto centers it horizontally.
.card .name — a descendant combinator targets the heading inside the card only, not every heading on a larger page. The margin: 0 0 8px 0 trims the browser's default heading spacing: none on top, 8px below.
.card p — a descendant plus element selector for the description line, so paragraphs outside cards are untouched.
.card .btn — the button stretches across the card's inner width (width: 100% of the content area) and gains comfortable padding for a clickable feel.
.card .btn:hover — a pseudo-class lightens the button while hovered, giving feedback without any JavaScript.
Nothing here is complicated on its own: a class, two combinators, one pseudo-class, and honest box sizing. That is genuinely the level of CSS behind most interfaces you use daily, and it is the exact vocabulary the next pages on Flexbox, Grid and media queries build on.
14. Advanced Selectors You Will Meet in Real Projects
Once the basic selectors feel comfortable, a small set of advanced patterns covers almost everything you will see in professional stylesheets. None of them are difficult — they just combine the ideas from part 1 in useful ways.
Attribute selectors
An attribute selector targets elements by an attribute they carry, written in square brackets. It is perfect when HTML structure varies but attributes stay predictable, which is very common in forms.
| Pattern | Matches when | Example |
[disabled] | The attribute is present at all | button[disabled] |
[type="text"] | The attribute equals that exact value | input[type="text"] |
[href^="https"] | The value begins with the text | a[href^="https"] |
[href$=".pdf"] | The value ends with the text | a[href$=".pdf"] |
/* give only text inputs a comfortable size */
input[type="text"] {
padding: 8px;
border: 1px solid gray;
}
/* show pointer cursor only on clickable, enabled buttons */
button:not([disabled]) {
cursor: pointer;
}
Negation with :not()
The :not() pseudo-class selects elements that do not match the condition inside the brackets. In the example above, button:not([disabled]) means "every button except disabled ones". It saves you from writing a style and then undoing it.
Position patterns with :nth-child()
Striped tables are the classic real-world use. Instead of adding a class to every second row by hand, let the browser count for you:
tbody tr:nth-child(even) {
background-color: whitesmoke;
}
If rows are ever added, removed or reordered, the stripes stay correct automatically. This is the kind of small automation that separates maintainable CSS from painful CSS.
15. Real-World Box Model Patterns
The centered page container
Nearly every website wraps its content in a container that is centered on wide screens but keeps a little breathing room on small screens. This three-line pattern is the skeleton of almost every responsive page, and the next pages of this module build directly on it:
.container {
max-width: 1100px;
margin: 0 auto;
padding: 0 16px;
}
Here is what each line does. max-width: 1100px lets the container grow on large screens but stop before becoming unreadably wide. margin: 0 auto centers it horizontally when there is spare space. padding: 0 16px guarantees that even on a narrow phone the content never touches the screen edges.
Handling margin collapse deliberately
Part 1 mentioned that vertical margins of neighbouring blocks collapse to the larger value. In real projects this shows up in two places. First, between stacked sections: a bottom margin of 40px meeting a top margin of 40px produces 40px of space, not 80px. Second, between a parent and its first child: the child's top margin can "leak" outside the parent and push the parent down instead of pushing the child away from the parent's top edge.
/* the child's margin-top escapes the parent */
.card {
background-color: white;
}
.card h3 {
margin-top: 24px; /* pushes the whole card down, not the heading down */
}
/* the fix: use padding on the parent instead */
.card {
background-color: white;
padding-top: 24px;
}
.card h3 {
margin-top: 0;
}
A simple rule of thumb many teams follow: space inside a component belongs to its padding, space between components belongs to margins, and use margin in one direction only (usually bottom) so collapsing never surprises you.
Small overlaps with negative margins
A negative margin pulls an element in the opposite direction. It is the easiest way to make a badge overlap the corner of an avatar or a heading sit slightly over an image:
.avatar-badge {
margin-top: -12px; /* pulls the badge up over the avatar above it */
}
Use it sparingly and for small distances — it is a finishing touch, not a layout system.
16. Common Mistakes and the Correct Way
Expecting width to include padding
/* without border-box this overflows its parent */
.sidebar {
width: 100%;
padding: 20px;
}
The actual box becomes 100% plus 40px, causing a horizontal scrollbar. The fix is the global reset you already know:
* {
box-sizing: border-box;
}
After that, width: 100% honestly means "fill the parent", with padding taken from inside.
Writing .card.name when you mean .card .name
/* wrong: matches an element with BOTH classes */
.card.name {
color: navy;
}
/* right: matches the .name element inside the .card element */
.card .name {
color: navy;
}
This single missing space is one of the most common beginner bugs. .card.name is a combined selector for one element; .card .name is a descendant combinator for two elements. When nothing styles as expected, check the spaces first.
Styling with IDs and then losing every override
#signup-btn {
background-color: navy;
}
/* this loses, even though it comes later */
.btn-primary {
background-color: darkgreen;
}
The ID scores far higher in specificity, so the later class rule can never win. The fix is to style with classes from the start and reserve IDs for things like form labels, anchors and JavaScript hooks.
Using margin where padding is needed
On a button, extra margin moves the button away from its neighbours but does not enlarge the clickable, coloured area. Extra padding grows the button itself, making it easier to tap and better looking. When in doubt: padding for space inside the element's own background, margin for space outside it.
Being surprised by collapsed section spacing
If you set margin-bottom: 40px on one section and margin-top: 40px on the next and expect 80px, you will get 40px. Fix it by keeping margins one-directional (bottom only) or by moving the spacing into padding where it must be guaranteed.
Writing selectors that mirror deep nesting
/* fragile: breaks when the HTML changes even slightly */
.header nav ul li a span {
color: navy;
}
/* robust: one class on the element you actually care about */
.nav-link-text {
color: navy;
}
Deep chains tie your CSS to the exact HTML structure. One meaningful class on the target element survives refactoring far better.
17. Best Practices for Selectors and Spacing
- Keep specificity low. Style with single class selectors so later rules can easily override earlier ones. Save IDs for hooks, not styling.
- Enable
border-box globally. Put the universal reset at the top of every stylesheet so all width arithmetic is predictable.
- Separate concerns. Padding for internal space, margin for external space, border for the visible edge. Do not fake one with another.
- Use a consistent spacing rhythm. Pick a small set of values such as 4, 8, 16, 24 and 32 pixels and reuse them, instead of inventing a new number for every gap.
- Let pseudo-classes do the work. Hover, focus and nth-child states belong in CSS, not in JavaScript or repeated HTML classes.
- Prefer one class on the target over long descendant chains that depend on exact nesting.
- Group related rules and order them consistently — for example, all card styles together, buttons together — so the next reader can find things quickly.
| Do | Avoid |
| Classes for styling, combined classes for variants | IDs and inline styles for styling |
A border-box reset at the top | Unpredictable width calculations |
| One-direction margin rhythm | Top and bottom margins that collapse unexpectedly |
| Short, meaningful class selectors | Selectors that mirror deep HTML nesting |
18. Practical Project: A Pricing Section from Scratch
This project uses every concept from the page: the universal reset, class selectors, a combined selector for a highlighted plan, descendant selectors, a pseudo-class, and careful box-model spacing. You will build a mobile-style pricing section where the plan cards are stacked; the next page of this module (Flexbox) will show how to place them side by side.
Step by step
- Create a file called
pricing.html and paste in the complete code below.
- Open it in your browser. You should see a centered column with three white plan cards on a light background.
- Notice the Pro card: its thicker green border comes from the combined selector
.plan.featured.
- Hover any button and watch the colour change — that is the
:hover pseudo-class.
- Open the browser DevTools, click a card, and look at the box model diagram in the Computed or Styles panel. Because of
border-box, each card's width fills the container exactly, with the 24px padding counted inside.
<!DOCTYPE html>
<html>
<head>
<style>
* {
box-sizing: border-box;
}
body {
margin: 0;
background-color: whitesmoke;
font-family: Arial, sans-serif;
}
.container {
max-width: 480px;
margin: 0 auto;
padding: 32px 16px;
}
.section-title {
text-align: center;
color: navy;
margin-top: 0;
margin-bottom: 24px;
}
.plan {
background-color: white;
border: 1px solid lightgray;
border-radius: 8px;
padding: 24px;
margin-bottom: 24px;
}
.plan.featured {
border: 2px solid darkgreen;
}
.plan h3 {
margin: 0 0 8px 0;
font-size: 18px;
color: dimgray;
}
.price {
margin: 0 0 16px 0;
font-size: 32px;
}
.price span {
font-size: 14px;
color: gray;
}
.plan ul {
list-style: none;
padding-left: 0;
margin: 0 0 20px 0;
color: dimgray;
}
.plan li {
padding: 6px 0;
border-bottom: 1px solid whitesmoke;
}
.plan button {
width: 100%;
padding: 10px;
border: none;
border-radius: 6px;
background-color: darkgreen;
color: white;
font-size: 16px;
}
.plan button:hover {
background-color: seagreen;
}
</style>
</head>
<body>
<div class="container">
<h2 class="section-title">Choose a plan</h2>
<article class="plan">
<h3>Basic</h3>
<p class="price">₹499 <span>per month</span></p>
<ul>
<li>Access to 20 lessons</li>
<li>Community forum</li>
<li>Email support</li>
</ul>
<button>Start Basic</button>
</article>
<article class="plan featured">
<h3>Pro</h3>
<p class="price">₹999 <span>per month</span></p>
<ul>
<li>Access to all lessons</li>
<li>Weekly live sessions</li>
<li>Project reviews</li>
</ul>
<button>Start Pro</button>
</article>
<article class="plan">
<h3>Team</h3>
<p class="price">₹2,499 <span>per month</span></p>
<ul>
<li>Everything in Pro</li>
<li>Five team seats</li>
<li>Priority support</li>
</ul>
<button>Contact us</button>
</article>
</div>
</body>
</html>
Check your understanding against the code: the container centers itself with margin: 0 auto and, thanks to border-box, its 480px limit already includes the 16px side padding, so each card is exactly 448px wide. Each card keeps its internal breathing room through padding and separates itself from the next card through a one-directional margin-bottom, so no collapsing surprises can occur.
19. Practice Exercises
- Build a small page with one
<h1>, two paragraphs and a button. Style the heading with an element selector, the paragraphs with a class, and the button with a combined selector such as .btn.primary.
- Create a five-row table and stripe it using
:nth-child(even), adding no classes in the HTML.
- Write a box with
width: 200px, padding: 20px and border: 5px solid black. Predict its rendered width under both content-box and border-box before checking in DevTools.
- Demonstrate the difference between
.a .b and .a.b with a tiny HTML file, and write down in one sentence when each matches.
- Center a 300px-wide card horizontally in the viewport using only
max-width and margins, then add side padding so it never touches the screen edge on small windows.
- Style a small form: text inputs via
input[type="text"], a visible :focus outline, and disabled buttons styled differently through :not([disabled]).
- Create two stacked sections where spacing must be exactly 40px, first with margins (observe the collapse), then with a one-direction margin, and compare.
- Take the pricing project and add a fourth plan of your own, reusing only existing classes — no new CSS except the data.
20. Interview Questions and Answers
What is the CSS box model and what are its layers?
It is the model the browser uses to render every element as a rectangle made of four layers: the content, the padding around the content, the border around the padding, and the margin outside the border. Padding and border can show the element's background; margin is always transparent space that separates the element from its neighbours.
What is the difference between margin and padding?
Padding is space inside the element, between its content and its border, and the element's background extends into it. Margin is space outside the border that pushes other elements away and never takes the background. On a button, padding makes the button itself bigger and more clickable; margin only moves it away from other elements.
What does box-sizing: border-box change?
It changes what the width and height properties mean. With the default content-box, they size only the content, so padding and border are added on top, making the box bigger than declared. With border-box, padding and border are included inside the declared width, so the box measures exactly what you typed. Most projects apply it to all elements with the universal selector because the arithmetic becomes predictable.
How does specificity decide which rule wins?
When several rules match the same element and set the same property, the browser compares selector strength: IDs rank above classes, which rank above element selectors. A convenient mental score is ids–classes–elements, compared left to right. If strength is equal, the rule written later in the stylesheet wins, and inline styles beat both.
What is the difference between .menu li and .menu > li?
.menu li is a descendant selector and matches every <li> anywhere inside the menu, at any nesting depth. .menu > li is a child selector and matches only those <li> whose direct parent is the menu. The child version is safer against unexpected wrapping elements; the descendant version is more flexible.
What is the difference between .card.featured and .card .featured?
.card.featured (no space) is one combined selector matching a single element that carries both classes at once. .card .featured (with a space) matches an element with class featured located anywhere inside an element with class card. The missing or extra space completely changes the meaning.
What are pseudo-classes and which ones do you use most?
They are selectors, written with a colon, that match an element in a particular state or position without any extra HTML. The everyday ones are :hover for pointer feedback, :focus for keyboard input fields, and :first-child or :nth-child() for positional patterns such as striped tables.
Why do vertical margins collapse and how do you prevent it?
When two vertical margins meet — between siblings, or between a parent and its first or last child — the browser uses only the larger value instead of adding both, so spacing can be smaller than expected and a child's margin can escape its parent. You prevent it by using one-directional margins, by replacing the child's margin with padding on the parent, or by introducing a border or padding between them.
How do you horizontally center a block-level element?
Give it a width or a max-width smaller than its parent, then set the left and right margins to auto, for example margin: 0 auto. The browser distributes the leftover space equally on both sides. This works for block elements with a defined width; it does not center inline content, which is handled with text alignment instead.
What does the universal selector do and when is it useful?
The star * matches every element on the page. Its main legitimate uses are global resets, most famously * { box-sizing: border-box; }, and broad normalisations such as resetting default margins at the start of a stylesheet. Because it matches everything, it should be used sparingly and deliberately.
Using the default content-box model, how do you compute an element's rendered width?
Add the content width, both horizontal paddings and both border widths. For example, width: 200px, padding: 20px and border: 5px render as 200 + 20 + 20 + 5 + 5 = 250px. Under border-box, the same declaration renders as exactly 200px.
When would you use an ID selector instead of a class selector?
Practically never for styling. An ID is unique on the page and scores very high in specificity, which makes later overrides difficult. Classes are reusable and keep specificity low, so they are the default tool. IDs are better reserved for anchors, form label associations and JavaScript lookups, where uniqueness is exactly what you want.
21. Quick Revision Checklist
- I can write element, class, ID and universal selectors from memory.
- I know that a space means "descendant" and no space means "same element must have all parts".
- I can name all four combinators and say what each one matches.
- I can explain
:hover, :focus and :nth-child() with an example each.
- I can rank selectors by specificity using the ids–classes–elements score.
- I can list the four box model layers in order: content, padding, border, margin.
- I know padding is inside the background and margin is outside it.
- I can compute a rendered width under both
content-box and border-box.
- I always start stylesheets with the
border-box universal reset.
- I use one-directional margins to avoid collapse surprises.
- I style with classes and keep specificity low.
- I can build a complete card-based component using only these concepts.
22. Official Documentation and Further Reading
When you are ready to test yourself against real interview material, the curated set at Frontend Interview Questions 2026: React, JS & CSS - Craqly collects frontend interview questions across React, JavaScript and CSS, including CSS layout questions that look simple but hide common traps — exactly the kind covered by the box model and specificity topics on this page.
Conclusion
Selectors and the box model are the two tools you will reach for in every stylesheet you ever write. Selectors decide who gets styled — through elements, classes, relationships and states — and the box model decides how much room each styled element occupies, with border-box making that arithmetic honest. Keep your specificity low, keep your spacing rhythm consistent, and verify your boxes in DevTools rather than guessing. With this foundation in place, the next pages on Flexbox and Grid become straightforward: they simply arrange the boxes you can now build and measure with confidence.
Learn more in the React JS Training course, or register for a course demo.