Skip to content
Tutorials Center
My learning

Topics

Lesson 138 of 139 ยท Practice and Review

CSS Practice Exercises

Practice CSS with 28 graded exercises on selectors, the cascade, the box model, flexbox, grid, responsive design and animation, each with a live editor and solution.

Reading about CSS and writing CSS are different skills. This page gives you 28 short exercises that cover the whole course, from your first selectors to cascade layers and container queries. Each one has a task, a live editor with starter code, and a solution hidden behind a Show solution button.

The exercises are grouped by topic and marked Beginner, Intermediate or Advanced. Try each one in the editor before you open the solution; struggling for a few minutes is how the rules stick. Your solution doesn't need to match ours exactly. If the result looks right and the CSS is simple, it's a good solution. When you get stuck, the link at the top of each group leads to the lesson that explains the topic.

Selectors

These practice Selector Basics, Combinators, Pseudo-classes, Structural Pseudo-classes and Pseudo-elements.

1. Target by context (Beginner)

Make every paragraph inside .intro dark blue (#1e3a8a) and every link inside <nav> bold. The paragraph outside .intro and the link outside <nav> must not change.

Exercise 1: context selectors
Show solution
CSS
.intro p {
  color: #1e3a8a;
}

nav a {
  font-weight: bold;
}

The descendant combinator (a space) limits each rule to elements inside the named ancestor.

2. Zebra table (Beginner)

Give every even body row of the table a light gray background (#f1f5f9), and highlight any row the pointer is over in light yellow (#fef9c3).

Exercise 2: zebra stripes
Show solution
CSS
tbody tr:nth-child(even) {
  background: #f1f5f9;
}

tbody tr:hover {
  background: #fef9c3;
}

Both selectors score (0, 1, 2), so the tie goes to the later rule and the hover color wins on striped rows too.

Without touching the HTML, add a small "โ†—" after every link whose href starts with https://, and make those links green. Internal links stay as they are.

Exercise 3: external links
Show solution
CSS
a[href^="https://"] {
  color: #15803d;
}

a[href^="https://"]::after {
  content: " โ†—";
}

^= matches the start of an attribute value, and ::after adds generated content inside the link, so it is underlined and clickable with it.

4. Finished tasks (Intermediate)

When a checkbox is checked, its whole list item should get a green border and its text should be struck through and gray. Use :has().

Exercise 4: style the parent
Show solution
CSS
li:has(input:checked) {
  border-color: #16a34a;
}

li:has(input:checked) span {
  color: #64748b;
  text-decoration: line-through;
}

li:has(input:checked) selects the list item that contains a checked box. Learn more in :is(), :where(), :not() and :has().

The cascade

These practice Specificity and Cascade Layers.

5. The stubborn button (Intermediate)

The Delete button should be red (.btn-danger), but a toolbar rule with an ID keeps it gray. Fix it without !important and without changing the HTML.

Exercise 5: lower the specificity
Show solution
CSS
:where(#toolbar) button {
  padding: 8px 14px;
  border: 0;
  border-radius: 6px;
  background: #e2e8f0;
  color: #0f172a;
}

#toolbar button scores (1, 0, 1), which beats one class. Wrapping the ID in :where() drops the selector to (0, 0, 1), so .btn-danger at (0, 1, 0) wins.

6. Utilities always win (Advanced)

The .text-red utility class should beat component styles no matter how specific they are. Put the rules into cascade layers so that's true, without editing any selector.

Exercise 6: cascade layers
Show solution
CSS
@layer components, utilities;

@layer components {
  .card .card-title { color: #1d4ed8; font-size: 1.25rem; }
}

@layer utilities {
  .text-red { color: #dc2626; }
}

Between layers, the later layer wins before specificity is even compared, so utilities beats components every time.

The box model

These practice The Box Model, box-sizing, Margins and Rounded Corners.

7. Same width, really (Beginner)

Both boxes have width: 200px, but the second one is wider on screen because of its padding and border. Make both exactly 200px wide, including padding and border, with one rule for all elements.

Exercise 7: box-sizing
Show solution
CSS
*, *::before, *::after {
  box-sizing: border-box;
}

With border-box, width includes padding and border, so the content area shrinks instead of the box growing.

8. A centered card (Beginner)

Turn the .card into a centered card: at most 24rem wide, centered horizontally, with 1.5rem padding, rounded corners and a soft shadow.

Exercise 8: centered card
Show solution
CSS
.card {
  max-width: 24rem;
  margin-inline: auto;
  padding: 1.5rem;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgb(15 23 42 / 12%);
}

margin-inline: auto splits the leftover space equally on both sides, which only works because the card has a maximum width.

9. Pills and circles (Beginner)

Make .badge a pill shape (fully rounded ends) and .avatar a 64px circle with its initials centered.

Exercise 9: border-radius shapes
Show solution
CSS
.badge {
  border-radius: 999px;
}

.avatar {
  display: grid;
  place-items: center;
  width: 64px;
  height: 64px;
  border-radius: 50%;
}

A huge radius is clamped to half the box height, giving pill ends; 50% on a square gives a circle.

Text, color and variables

These practice Styling Text, Wrapping, Overflow and Hyphens and Custom Properties.

10. A readable article (Beginner)

Make the article comfortable to read: a system font stack, line height 1.6, lines no longer than about 60 characters, and a heading with slightly tighter line height and 0.02em letter spacing.

Exercise 10: readable text
Show solution
CSS
article {
  max-width: 60ch;
  font-family: system-ui, sans-serif;
  line-height: 1.6;
}

article h1 {
  line-height: 1.2;
  letter-spacing: 0.02em;
}

The ch unit is based on the width of the "0" character, which makes it a natural unit for line length.

11. One-line titles (Intermediate)

The product title is too long for its box. Keep it on one line and end it with "โ€ฆ" where it's cut off.

Exercise 11: ellipsis
Show solution
CSS
.title {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

All three are needed: no wrapping, hide what overflows, and show the ellipsis. Add a title attribute or show the full name elsewhere so nothing is lost.

12. A themeable button (Intermediate)

Define a --brand custom property on :root (#2563eb) and use it for the button background and the link color. Then make .theme-green switch both to #16a34a by changing only the variable.

Exercise 12: custom properties
Show solution
CSS
:root {
  --brand: #2563eb;
}

.theme-green {
  --brand: #16a34a;
}

.btn {
  background: var(--brand);
}

a {
  color: var(--brand);
}

Custom properties inherit, so redefining --brand on a section changes every var(--brand) inside it.

Backgrounds and images

These practice Gradients and Sizing Images: object-fit and aspect-ratio.

13. A gradient banner (Beginner)

Give the banner a diagonal gradient from #7c3aed to #db2777, white text, generous padding and rounded corners.

Exercise 13: gradient banner
Show solution
CSS
.banner {
  padding: 2rem;
  border-radius: 16px;
  color: white;
  background: linear-gradient(135deg, #7c3aed, #db2777);
}

135deg runs the gradient from the top-left corner toward the bottom-right.

14. Square thumbnails (Intermediate)

Show the images as a row of square thumbnails, each 120px wide, cropped to fill the square without stretching.

Exercise 14: object-fit
Show solution
CSS
.gallery img {
  width: 120px;
  aspect-ratio: 1;
  object-fit: cover;
  border-radius: 8px;
}

aspect-ratio makes each box square, and object-fit: cover scales the image to fill it, cropping the overflow.

Positioning

These practice Positioning and z-index and Stacking Contexts.

15. A notification badge (Intermediate)

Pin the red .count badge to the top-right corner of the button, half outside it.

Exercise 15: absolute positioning
Show solution
CSS
.inbox {
  position: relative;
}

.count {
  position: absolute;
  top: 0;
  right: 0;
  translate: 50% -50%;
}

position: relative on the button makes it the containing block, and the translate shifts the badge half its own size outward.

16. A sticky header (Intermediate)

Make the list heading stay at the top of the scrolling box while you scroll through the items.

Exercise 16: sticky
Show solution
CSS
h2 {
  position: sticky;
  top: 0;
}

A sticky element scrolls normally until it reaches top: 0 inside its scroll container, then stays there.

Flexbox

These practice Flexbox Basics, Flex Item Properties and Flexbox Patterns.

17. A simple navbar (Beginner)

Put the logo on the left and the links on the right, all vertically centered, with 1rem between the links.

Exercise 17: navbar
Show solution
CSS
.bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.links {
  display: flex;
  gap: 1rem;
}

space-between pushes the two children to opposite ends; the nested flex container spaces the links with gap.

18. Buttons at the bottom (Intermediate)

The cards already have equal heights, but their buttons sit at different heights. Line up every button at the bottom of its card.

Exercise 18: push to the bottom
Show solution
CSS
.card {
  display: flex;
  flex-direction: column;
}

.card button {
  margin-top: auto;
}

In a column flex container, an auto top margin absorbs all the free space above the button and pushes it down.

19. The media object (Intermediate)

Put the 64px image beside the text. The text should fill the remaining width, and the long unbroken word must not make the row overflow.

Exercise 19: media object
Show solution
CSS
.media {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.media img {
  flex: none;
}

.media .body {
  flex: 1;
  min-width: 0;
  overflow-wrap: anywhere;
}

Flex items won't shrink below their content by default; min-width: 0 allows it, and overflow-wrap: anywhere breaks the long word.

Grid

These practice Grid Basics, Grid Tracks, Placing Grid Items and Grid Template Areas.

20. A three-column grid (Beginner)

Arrange the tiles in three equal columns with a 10px gap. The first tile should span two columns.

Exercise 20: grid columns
Show solution
CSS
.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}

.tile:first-child {
  grid-column: span 2;
}

span 2 stretches the first tile over two tracks, and the other tiles flow into the remaining cells.

21. A responsive card grid (Intermediate)

Make the cards fill as many columns as fit, each at least 140px wide, stretching to fill the row, with no media queries. Resize the preview to test.

Exercise 21: auto-fit
Show solution
CSS
.cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 12px;
}

auto-fit creates as many 140px-minimum columns as fit, and the 1fr maximum shares any leftover space between them.

22. A page layout with areas (Advanced)

Build the page shell with grid-template-areas: header and footer across the full width, a 10rem sidebar beside the main content, and the main row taking all leftover height. On screens narrower than 30rem, stack everything in one column.

Exercise 22: grid areas
Show solution
CSS
.page {
  display: grid;
  min-height: 100vh;
  grid-template-columns: 1fr;
  grid-template-rows: auto auto 1fr auto;
  grid-template-areas: "header" "nav" "main" "footer";
}

@media (width >= 30rem) {
  .page {
    grid-template-columns: 10rem 1fr;
    grid-template-rows: auto 1fr auto;
    grid-template-areas:
      "header header"
      "nav    main"
      "footer footer";
  }
}

header { grid-area: header; }
nav    { grid-area: nav; }
main   { grid-area: main; }
footer { grid-area: footer; }

The base styles are the single column (mobile first), and the media query redraws the map once there is room for a sidebar.

Responsive design

These practice Media Queries, Mobile-First CSS and Container Queries.

23. Mobile first (Intermediate)

The two columns should stack on narrow screens and sit side by side, with a 1rem gap, when the viewport is at least 28rem wide. Write the stacked layout as the default.

Exercise 23: media query
Show solution
CSS
@media (width >= 28rem) {
  .row {
    display: flex;
    gap: 1rem;
  }

  .col {
    flex: 1;
    margin-bottom: 0;
  }
}

Block layout stacks the columns by default, so the only CSS needed is the wider-screen enhancement.

24. A card that adapts to its box (Advanced)

Drag the corner of the dashed box to resize it. Make the card switch to a horizontal layout (image left, text right) when its container is at least 22rem wide.

Exercise 24: container query
Show solution
CSS
.wrap {
  container-type: inline-size;
}

@container (width >= 22rem) {
  .card {
    grid-template-columns: 8rem 1fr;
    align-items: center;
  }
}

container-type: inline-size makes the wrapper a query container, and @container responds to its width instead of the viewport's.

Transitions and animation

These practice Transitions, Keyframe Animations and Motion, Performance and prefers-reduced-motion.

25. A lifting button (Beginner)

On hover and keyboard focus, the button should move up 3px and turn darker blue (#1d4ed8), animating smoothly over 150ms.

Exercise 25: transition
Show solution
CSS
.btn {
  transition: background-color 150ms ease, translate 150ms ease;
}

.btn:is(:hover, :focus-visible) {
  background-color: #1d4ed8;
  translate: 0 -3px;
}

The transition goes on the base state so the change animates in both directions; :focus-visible gives keyboard users the same feedback.

26. A loading spinner (Intermediate)

Turn the .spinner into a spinning ring: a 40px circle with a light border and one blue side, rotating once per second forever. People who prefer reduced motion should get a slower spin.

Exercise 26: keyframes
Show solution
CSS
.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #e2e8f0;
  border-top-color: #2563eb;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { rotate: 1turn; }
}

@media (prefers-reduced-motion: reduce) {
  .spinner { animation-duration: 3s; }
}

Only one border side is colored, so rotation is visible. A slow spin keeps the "busy" signal without fast motion.

Modern CSS

These practice CSS Nesting, Dark Mode and Feature Queries.

27. Nest it (Advanced)

Rewrite the four flat rules as one nested .alert rule. The result must look exactly the same.

Exercise 27: nesting
Show solution
CSS
.alert {
  padding: 12px 16px;
  border-left: 4px solid #f59e0b;
  background: #fffbeb;

  & h3 { margin: 0 0 4px; font-size: 1rem; }
  & p { margin: 0; }

  &.is-error {
    border-color: #dc2626;
    background: #fef2f2;
  }
}

&.is-error (no space) means "this same element also has .is-error"; & h3 means an h3 inside it.

28. Automatic dark mode (Advanced)

Use custom properties for the page background, text and card colors, then switch them in a prefers-color-scheme: dark media query. Also tell the browser the page supports both schemes so form controls and scrollbars match. Test it by switching your system theme.

Exercise 28: dark mode
Show solution
CSS
:root {
  color-scheme: light dark;
  --bg: #f8fafc;
  --text: #0f172a;
  --surface: #ffffff;
}

@media (prefers-color-scheme: dark) {
  :root {
    --bg: #0f172a;
    --text: #e2e8f0;
    --surface: #1e293b;
  }
}

body { background: var(--bg); color: var(--text); }
.card { background: var(--surface); }

Only the variables change in dark mode; every rule that uses them updates automatically. color-scheme restyles built-in controls.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A rule #menu a keeps overriding your .link-active class. What's the cleanest fix?

    :where() removes the ID's specificity, so the class can win normally without an arms race.
  2. 2. Which pair pushes a button to the bottom of a card?

    In a column flex container, an auto margin takes all free space above the button.
  3. 3. Why does a flex item with a very long word overflow its container?

    Set min-width: 0 on the item (and let the text wrap) to allow it to shrink.
  4. 4. What makes an element a container that @container rules can query?

    You must opt in with container-type (or the container shorthand) on the ancestor you want to measure.

Summary

  • Selectors practice: context, structural, attribute and :has() selectors cover most targeting needs.
  • Cascade practice: lower specificity with :where() and order whole groups of rules with @layer, instead of reaching for !important.
  • Layout practice: border-box sizing, auto margins, flexbox for rows, grid for two-dimensional layouts and auto-fit + minmax() for responsive grids.
  • Responsive practice: write mobile-first defaults, then add media queries and container queries.
  • Motion practice: animate transform, translate and opacity, and respect reduced motion.
  • If an exercise felt hard, revisit its linked lesson, then try it again tomorrow without looking.

Next: CSS Interview Questions โ€” test your understanding with the questions interviewers ask most.