My account

CSS

The browser picks only one value for each property, and this choice has rules: the cascade, specificity and order. Once you understand these rules, the box model and the difference between Flexbox and Grid, you no longer need important or huge z-index numbers. Start the page from mobile, keep colours in variables, and animate only transform and opacity.

Not reviewedWritten with AI helpReading time: 14 minOnline shop exampleCSS code

Author: bezzad

Contents

The problem: CSS that works by force

Our online shop has three open bugs:

  1. The “Add to cart” button does not get the new green colour. An old rule with an ID in its selector is stronger, so the new rule never wins.
  2. On phones, a long product name sticks out of its card, and the page scrolls sideways.
  3. The login window with a z-index of 9999 is still under the page header.
#product-list .card .btn { background: gray; }
.btn-primary { background: green; } /* never wins */

None of this is magic. Each one has a clear rule.

The cascade: which rule wins?

When several rules set one property on one element, the browser compares them in this order. The first step that has a winner decides:

  1. Importance and origin. Important rules beat normal rules. The site’s CSS beats the browser’s default CSS.
  2. Inline style. The style attribute on the element itself beats any selector.
  3. Layers (cascade layers). If you use the layer rule, the later layer wins. More on this below.
  4. Specificity of the selector.
  5. Order. If everything else is equal, the rule written last wins.

Counting specificity

Each selector has three numbers. Compare them like the digits of a number, from left to right:

  1. First column: the number of IDs.
  2. Second column: the number of classes, attribute selectors and pseudo-classes like hover.
  3. Third column: the number of tags and pseudo-elements like before.
  4. The star (the universal selector) and combinators like a space or the greater-than sign add nothing.
a { }               /* 0-0-1 */
.price { }          /* 0-1-0 */
.card .price { }    /* 0-2-0 */
nav a:hover { }     /* 0-1-2 */
#cart .item a { }   /* 1-1-1 */
SelectorIDClass, pseudo-classTag.card .price020nav a:hover012#cart .item a111Compare left to right, like the digits of a numberWinner: it has one ID
The left column is compared first. One ID beats any number of classes, so the last rule wins.
  1. The where pseudo-class always has zero specificity. It is good for base styles that must be easy to override.
  2. The is, not and has pseudo-classes count as the most specific selector inside them.
  3. That is why in the code above the btn-primary class rule, with specificity 0-1-0, cannot reach 1-2-0.

The fix is not important. The fix is to keep selectors short and light: one class for each thing. Do not use IDs for styling.

Inheritance

Some properties pass from parent to child, and some do not:

  1. Text properties like color, font-family and line-height are inherited. Write them once on the body, and the whole page gets them.
  2. Box properties like margin, padding, border and background are not inherited.
  3. The inherit keyword forces any property to take the parent’s value.
.card {
  color: #333;          /* children inherit this */
  border: 1px solid #ddd; /* children do not */
}

The box model and box-sizing

Every element is a box: the content, padding around it, a border around that, and margin outside.

  1. The default value of box-sizing is content-box. So width is only the content width, and padding and border are added to it.
  2. With border-box, the width includes padding and border. The maths is simpler.
  3. That is why most projects put this rule at the start of their CSS:
*, *::before, *::after {
  box-sizing: border-box;
}

.card {
  width: 300px;
  padding: 20px;
  border: 2px solid #ddd;
}
marginborderpaddingcontentThe parts of a boxbox-sizing: content-boxcontent 300Real width: 344 pixelsbox-sizing: border-boxcontent 256Real width: 300 pixels
With content-box, the card is really 344 pixels wide. With border-box, it stays 300 pixels, and the content has 256 pixels.
Margin collapse. Between two blocks, one above the other, vertical margins are not added together. The larger of the two stays. This does not happen inside a flex or grid container.

Flexbox or Grid?

  1. Flexbox is one-dimensional: one row or one column. Sizes start from the content. It is good for a header, a toolbar and a cart row.
  2. Grid is two-dimensional: rows and columns together. You first define the grid, then place things in it. It is good for the product list and the whole page layout.
  3. You can use both together: Grid for the page, Flexbox inside each card.
/* Header: one row, the search box takes the free space */
.header {
  display: flex;
  align-items: center;
  gap: 1rem;
}
.header .search { flex: 1; }

/* Product list: as many columns as fit, each at least 12rem */
.products {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(12rem, 1fr));
  gap: 1rem;
}
Flexbox: one directionlogosearchflex: 1cartOnly one axisFor a header, a toolbar and a cart rowGrid: two directionscardcardcardcardcardcardFor the product list and the page layout
Flexbox places things in one direction. Grid builds a table of rows and columns.

The min-width trap in Flexbox

  1. Flex items have min-width set to auto by default.
  2. This means an item does not get smaller than its content.
  3. So a long product name with no spaces pushes the cart row out of the screen. This is our second bug.
  4. The fix: set min-width to zero on the item that must shrink.
.cart-row { display: flex; gap: 1rem; }

.cart-row .name {
  flex: 1;
  min-width: 0;            /* allow it to shrink */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

Positioning and stacking context

  1. The value relative keeps the element in its place and makes it the reference for absolute children.
  2. The value absolute takes the element out of the page flow and places it relative to the nearest positioned ancestor.
  3. The value fixed fixes the element to the screen.
  4. The value sticky keeps the element normal until it reaches an edge, then it sticks there.
.card { position: relative; }
.card .badge { position: absolute; top: 0.5rem; inset-inline-end: 0.5rem; }

.header { position: sticky; top: 0; z-index: 10; }

The z-index property is compared only inside one stacking context. This is our third bug:

.header  { position: sticky; z-index: 10; }
.content { position: relative; z-index: 1; } /* new stacking context */
.content .login-modal { position: fixed; z-index: 9999; }
  1. The content container, with position and z-index, makes a new stacking context.
  2. The login window is inside it. The number 9999 is compared only with the other children of content.
  3. The whole content container, at 1, is compared with the header, at 10. So everything inside it is under the header.
  4. Other things also make a stacking context: opacity below 1, transform, filter, and isolation with the value isolate.
  5. The fix: put the window outside that container, or use the dialog tag with the showModal method. This method puts the window in the top layer, which is above everything.

Responsive design

  1. Start from mobile (mobile first). The base styles are for a small screen. Then add things for bigger screens with min-width.
  2. The media rule looks at the screen size. It is good for the page layout.
  3. The container rule looks at the size of the component’s own container. A product card lays itself out right in a narrow column and in a wide one.
  4. Prefer relative units. The rem unit depends on the root font size and grows with the user’s font setting. The em unit depends on the element’s own font, and the vw unit on the screen width.
  5. The clamp function takes a minimum, a preferred value and a maximum. The size changes smoothly between the two limits.
/* Mobile first: one column */
.products { grid-template-columns: 1fr; }

@media (min-width: 48rem) {
  .products { grid-template-columns: repeat(3, 1fr); }
}

/* The card looks at its own container, not the screen */
.card-wrap { container-type: inline-size; }

@container (min-width: 25rem) {
  .card { display: flex; gap: 1rem; }
}

h1 { font-size: clamp(1.5rem, 1rem + 2vw, 2.5rem); }
Do not size fonts with vw alone. A size written only in vw does not grow when the user changes the browser’s font size. Add a rem part next to it, as in the code above.

CSS variables for themes and dark mode

CSS variables (custom properties) start with two dashes. They are inherited by default, and they can change at run time.

:root {
  --bg: #ffffff;
  --text: #1a1a1a;
  --accent: #0a7d4f;
  color-scheme: light dark;
}

@media (prefers-color-scheme: dark) {
  :root {
    --bg: #121212;
    --text: #eeeeee;
    --accent: #4cc38a;
  }
}

body { background: var(--bg); color: var(--text); }
.btn-primary { background: var(--accent); }
  1. Colours are defined in one place. The rest of the CSS only knows the variable name.
  2. For dark mode, only the values of the variables change, not the rules.
  3. The color-scheme property tells the browser that the page supports both modes, so form fields and scrollbars get the right colours too.
  4. If the user wants to pick the theme, change the same variables on an attribute like data-theme.

Cascade layers

The layer rule makes the order of CSS groups explicit:

@layer reset, base, components, utilities;

@layer components {
  #checkout .btn { background: var(--accent); }
}

@layer utilities {
  .bg-gray { background: gray; } /* wins: later layer */
}
  1. The later layer wins, even with lower specificity.
  2. CSS outside any layer beats all layers.
  3. The benefit: put library CSS in a low layer. You no longer need long selectors or important to override it.

Animation: transform and opacity, not top and left

  1. The browser has three jobs for each frame: working out the layout, painting, and compositing the layers.
  2. Changing top, left or width changes the layout. The browser must redo layout and paint in every frame. On a weak phone, the animation stutters.
  3. Changing transform and opacity usually needs only the compositing step and runs smoothly.
.cart-drawer {
  transform: translateX(100%);
  transition: transform 200ms ease;
}
.cart-drawer.open { transform: translateX(0); }

@media (prefers-reduced-motion: reduce) {
  .cart-drawer { transition: none; }
}
Less motion. Some users turn on the reduce motion option in their operating system, because motion makes them feel sick. Respect this choice with prefers-reduced-motion.

Common mistakes

Mistake Result Better way
Using important to win The next rule needs important too. Short selectors with one class. Layers.
Styling with IDs Hard to override. Classes.
Forgetting box-sizing The card is wider than the number you wrote. The border-box rule for all elements.
Using Flexbox for the product table Columns do not line up across rows. Grid.
Ignoring min-width auto Long text sticks out of the flex row. Set min-width to zero.
A bigger z-index number Still under the header. Find the stacking context, or use the dialog tag.
Starting from desktop and shrinking A lot of fragile code for phones. Start from mobile and grow with min-width.
Font size in vw only Does not grow with the user’s font setting. The clamp function with a rem part.
Fixed colours everywhere Dark mode means rewriting every rule. CSS variables.
Animating top and left Stuttering motion on phones. The transform and opacity properties.

Summary in seven lines

  1. The browser finds the winner in this order: importance and origin, inline style, layer, specificity, order.
  2. For specificity, compare the ID column, then classes, then tags. Keep selectors short.
  3. Text properties are inherited, box properties are not. With border-box, width includes padding and border.
  4. Flexbox for one direction, Grid for rows and columns. If a flex item does not shrink, set min-width to zero.
  5. A z-index number only has meaning inside its own stacking context.
  6. Start from mobile, use media for the page and container for components, and keep colours in variables.
  7. Animate only transform and opacity, and respect reduced motion.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.