bhylu.com

Advertisements

Sass Parent Selector

Use ampersand when a state belongs to the current component itself.

How it works

The parent selector & refers to the outer selector in a nested Sass rule. Appending a state such as :focus-visible or a modifier class creates a relationship different from an ordinary descendant. Keep selector lists in mind because one nested rule can expand to several selectors.

Run the code

Use Dart Sass 1.107.0 in a separate learning folder. Install Node.js, then run npm install --save-dev --save-exact sass@1.107.0. Save every file below with its shown path. Run npx sass parent-selector.scss parent-selector.css --no-source-map from that folder. Browsers receive compiled CSS, not Sass.

The existing Sass playground uses legacy LibSass 3.6.2 and cannot run modern modules. The compiled CSS preview uses the isolated HTML/CSS editor; it does not compile Sass online. Preloading does not execute the preview. Apache, MySQL and PHP are not required.

Example

parent-selector.scss

Download parent-selector.scss — save at the shown relative path.

parent-selector.scss

.screening-card {
  &.featured {
    border: 2px solid #0078d4;
  }
  .title {
    font-weight: 600;
  }
}

Expected CSS

Expected CSS

.screening-card.featured {
  border: 2px solid #0078d4;
}
.screening-card .title {
  font-weight: 600;
}

The featured class must be on the same element as screening-card. The title still belongs to a descendant. A context prefix such as .programme & would reverse where the outer selector appears, which should be reviewed in generated CSS.

Preview compiled CSS — choose Run code. Change and compile Sass locally first.

Technical reference: official Sass documentation. Original fictional film-club examples; no booking service is provided.