less
  1. less-extend

Extend - (Less Basics)

In Less, the extend directive allows you to reuse styles from one selector in another selector. This can help to keep your styles DRY (don't repeat yourself) and reduce the amount of code you need to write. In this tutorial, we'll discuss the syntax, example, output, explanation, use, important points, and summary of extend in Less.

Syntax

The syntax for extend in Less is as follows:

selector:extend(other-selector) {
  /* styles to be extended go here */
}
  • selector: The selector that you want to extend from.
  • other-selector: The selector that you want to extend to.

Example

Let's illustrate the use of extend with an example. Here, we'll define a set of base styles for an button and then extend those styles for a special, primary button:

.btn {
  padding: 10px 20px;
  border-radius: 5px;
  background-color: #ccc;
  color: #333;

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

.btn-primary:extend(.btn) {
  background-color: #0074D9;
  color: #fff;
}

In this example, we define a basic .btn class with some default styles and styles for the :hover pseudo-class. Then, we extend those styles with the .btn-primary class, which includes the background-color and color properties for a bright blue button with white text.

Output

When the above Less code is compiled, the following CSS code will be produced:

.btn, .btn-primary {
  padding: 10px 20px;
  border-radius: 5px;
  background-color: #ccc;
  color: #333;
}

.btn:hover, .btn-primary:hover {
  background-color: #ddd;
}

.btn-primary {
  background-color: #0074D9;
  color: #fff;
}

Explanation

In this example, the :extend() pseudo-class is used to extend the styles of the .btn selector to the .btn-primary selector. This means that .btn-primary will inherit all of the styles of .btn, and any additional styles that are defined exclusively for .btn-primary will be applied in addition to those inherited styles.

Use

The extend directive is useful when you have a set of base styles that you want to reuse in other selectors without repeating the same code. This can make your stylesheets more compact, readable, and easier to maintain.

Important Points

  • The extend directive only works on whole selectors, not individual properties.
  • The & symbol refers to the parent selector.
  • If a property with the same name is defined in both the base selector and the extending selector, the property values from the extending selector will be applied.
  • You can extend more than one selector by separating the selectors with commas in the extend declaration.

Summary

In this tutorial, we discussed the extend directive in Less. We covered the syntax, example, output, explanation, use, and important points of extend. With this knowledge, you can now use extend in your Less stylesheets to reduce code duplication, keep your code DRY, and make your stylesheets more readable and maintainable.

Published on: