CodeBlanks Logo Icon CodeBlanks

Summary - Component style

CSS course · Expert · Lesson 48/53

Build component styles with nesting.

Components with nesting

Nesting gathers every part of a component into one block. Inside .profile-card, the heading, paragraph, hover state and small-screen behavior sit together; the stylesheet mirrors the HTML.

In this summary we bring it all together: base styles, pseudo-classes, compound selectors and responsive behavior in one block.

Keep it shallow

Nesting is powerful, but as it deepens, selector specificity rises and reading gets harder. Going more than three levels deep is usually a bad idea; it keeps styles simpler.

A component's root, its children and its pseudo-classes are usually enough. If you need deeper nesting, it may signal that the HTML structure could be simplified.

Exercise Profile card styles

Add three nested blocks inside the .profile-card selector: an h2 selector with color: navy, an &:hover pseudo-class with background: #f5f5f5, and an &.featured compound selector with border: 2px solid navy.

Show example solution
Add three blocks inside .profile-card.
Example solution:
/* add sections inside .profile-card */
.profile-card {
  padding: 1rem;
  h2 {
    color: navy;
  }
  &:hover {
    background: #f5f5f5;
  }
  &.featured {
    border: 2px solid navy;
  }
}

Exercise Add a dark theme

Add a @media (prefers-color-scheme: dark) block inside the .profile-card selector with background: #111 and color: #eee.

Show example solution
Add a @media block inside .profile-card.
Example solution:
/* add dark theme inside .profile-card */
.profile-card {
  padding: 1rem;
  @media (prefers-color-scheme: dark) {
    background: #111;
    color: #eee;
  }
}

Test yourself

  1. Match each concept to its snippet

    Descendant
    .card { p { } }
    Pseudo-class
    .card { &:hover { } }
    Suffix
    .btn { &-primary { } }
    Compound class
    .tab { &.active { } }
  2. Complete the component

    /* profile card */
    .profile-card {
      padding: 1rem;
      ____ {
        color: navy;
      }
    }
    Show answer
    /* profile card */
    .profile-card {
      padding: 1rem;
      &:hover {
        color: navy;
      }
    }

All lessons in Expert