MakeW3web

Nesting and inheritance

Nesting and inheritance are two powerful features in Sass that allow you to write more concise and maintainable CSS code.

Nesting

Nesting in Sass allows you to write CSS rules in a hierarchical way, which can make your code more organized and easier to read. Here's an example:

nav {
  ul {
    margin: 0;
    padding: 0;
    list-style: none;
  }

  li {
    display: inline-block;

    a {
      text-decoration: none;
      padding: 10px;
    }
  }
}

In this example, we're nesting the `ul`, `li`, and `a` elements inside the `nav` element. This allows us to write more specific CSS rules without having to repeat the parent selector over and over again.

Inheritance

Inheritance in Sass allows you to define a set of styles that can be inherited by other elements. This can help you to write less code and keep your styles consistent across your site. Here's an example:

%button {
  display: inline-block;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  text-align: center;
  text-decoration: none;
  color: #fff;
  background-color: #007bff;
  cursor: pointer;
}

.button-primary {
  @extend %button;
}

.button-secondary {
  @extend %button;
  background-color: #6c757d;
}

In this example, we're defining a placeholder selector called `%button` that contains a set of styles that we want to reuse. We then use the `@extend` directive to inherit those styles in our `.button-primary` and `.button-secondary` classes. This allows us to write less code and keep our button styles consistent across our site.

Was this page helpful?