0
0
SASSmarkup~5 mins

Parent selector with & in SASS

Choose your learning style9 modes available
Introduction
The parent selector & helps you write CSS rules that relate to the current selector without repeating it. It keeps your styles organized and easy to read.
When you want to style a child element based on its parent class.
When you need to add a hover effect or state style to the same element.
When you want to create nested styles without repeating the full selector.
When you want to combine the parent selector with pseudo-classes like :hover or :focus.
When you want to write cleaner and shorter CSS code.
Syntax
SASS
& { /* nested styles here */ }
The & symbol represents the current parent selector in Sass nesting.
You can combine & with other selectors or pseudo-classes like &:hover or &-modifier.
Examples
Creates a class .button-primary by combining & with -primary.
SASS
.button {
  &-primary {
    color: blue;
  }
}
Adds a hover style to the .nav element using &.
SASS
.nav {
  &:hover {
    background: lightgray;
  }
}
Styles a child element with class .title inside .card.
SASS
.card {
  & .title {
    font-weight: bold;
  }
}
Sample Program
This Sass code styles a container with a background and padding. It creates a .container-header class for the header style, adds a hover effect on .container, and styles a child .content element inside .container.
SASS
@charset "UTF-8";

.container {
  background-color: #f0f0f0;
  padding: 1rem;

  &-header {
    font-size: 1.5rem;
    color: #333;
  }

  &:hover {
    background-color: #e0e0e0;
  }

  & .content {
    margin-top: 1rem;
    color: #666;
  }
}
OutputSuccess
Important Notes
The & selector always refers to the full parent selector, so you can build complex selectors easily.
Using & helps avoid repeating long class names and keeps your Sass code DRY (Don't Repeat Yourself).
Remember to compile your Sass to CSS before using it in a browser.
Summary
The & symbol in Sass means the current parent selector.
It helps write nested, cleaner CSS without repeating selectors.
You can combine & with other selectors or pseudo-classes for flexible styling.