乐闻世界logo
搜索文章和话题

What does % mean in SASS?

1个答案

1

In SASS, the % symbol is primarily used to define an inherited style, which is referred to as the placeholder selector in SASS. Styles defined with % do not produce any CSS output by themselves unless they are referenced by the @extend directive in other selectors.

Purpose and Benefits

The main purpose of placeholder selectors is to help us create reusable style modules without worrying about generating redundant code. When using class selectors (e.g., . ) to create generic styles, unused styles will still appear in the generated CSS file. With placeholder selectors, only when these styles are actually referenced are they included in the final CSS file.

Example

The example below demonstrates the use of a SASS placeholder selector:

scss
// Define a placeholder selector %text-shared-style { font-family: Arial, sans-serif; color: blue; font-size: 14px; } // Reference the placeholder selector using @extend .error-message { @extend %text-shared-style; color: red; } // Reference the placeholder selector using @extend .info-message { @extend %text-shared-style; color: green; }

In the above example, %text-shared-style is a placeholder selector that defines common text styles. Instead of directly using class or element selectors, we reference these styles using @extend in .error-message and .info-message. Thus, only where .error-message and .info-message are actually used will the styles defined in %text-shared-style be output to the CSS file, with the appropriate color modifications applied.

This approach reduces redundant code, improves CSS maintainability and extensibility, and helps keep the stylesheet clean and organized.

2024年7月20日 15:50 回复

你的答案