When encountering code like this in CSS, it's natural to wonder about the significance of the ampersand (&) character:
.clearfix {
*zoom: 1;
&:before,
&:after {
display: table;
content: "";
}
&:after {
clear: both;
}
}
However, it's important to note that this syntax is not part of CSS. Instead, it belongs to a CSS preprocessor called LESS.
LESS allows you to nest selector modifiers using the ampersand character. This enables you to write concise and readable code by avoiding repetition. For instance:
.clearfix {
&:before {
content: '';
}
}
This will compile to:
.clearfix:before {
content: '';
}
The ampersand ensures that the nested selectors compile to .clearfix:before. Without it, they would compile to .clearfix :before, which would result in an invalid CSS selector.
In the Twitter Bootstrap example you provided, the ampersand is used to apply styles to pseudo-elements (::before and ::after) that are created as children of the .clearfix element. This allows you to define these pseudo-elements concisely and maintain a modular structure within your CSS.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3