Home > Web Front-end > CSS Tutorial > How does the ampersand (&) work in LESS when used with CSS pseudo elements?

How does the ampersand (&) work in LESS when used with CSS pseudo elements?

Susan Sarandon
Release: 2024-10-26 18:59:29
Original
934 people have browsed it

How does the ampersand (&) work in LESS when used with CSS pseudo elements?

Ampersands in CSS Pseudo Elements: A LESS Trick

In CSS, the ampersand (&) is typically used in conjunction with pseudo elements, such as :before and :after. However, in the example provided from Twitter Bootstrap, the ampersand is used in a slightly different way.

The syntax in question is:

<code class="css">.clearfix {
  *zoom: 1;
  &:before,
  &:after {
    display: table;
    content: "";
  }
  &:after {
    clear: both;
  }
}</code>
Copy after login

Upon closer inspection, we realize that this is not pure CSS but LESS, a popular CSS preprocessor. In LESS, the ampersand allows for selector nesting. By prefixing the pseudo elements with the parent selector (&), we can achieve the following:

<code class="less">.clearfix {
  &:before {
    content: '';
  }
}</code>
Copy after login

This will compile to:

<code class="css">.clearfix:before {
  content: '';
}</code>
Copy after login

Without the ampersand, the selectors would compile to .clearfix :before, which is not a valid CSS syntax. Therefore, in LESS, the ampersand is used to nest selector modifiers, allowing for more concise and readable code.

The above is the detailed content of How does the ampersand (&) work in LESS when used with CSS pseudo elements?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template