Home >Web Front-end >CSS Tutorial >How Can I Generate a Comma-Separated List of CSS Classes Dynamically in SCSS?
Creating Dynamic Class Lists with Comma Separation
The ability to dynamically create a list of classes with commas separating them plays a vital role in CSS and SCSS, particularly when constructing responsive layouts.
Consider the case of a SCSS grid system: You want to create a dynamic grid system using $columns as a variable to determine the number of columns. While using @mixin col-x to generate individual class widths works effectively, the challenge arises when trying to create a comma-separated list of these classes.
Solving the Logic Issue
@extend in SCSS provides the solution to this challenge. By defining a new mixin called col-x-list that includes a placeholder %float-styles containing the desired styling (float: left), you can seamlessly apply these styles to multiple classes using @extend:
$columns: 12; %float-styles { float: left; } @mixin col-x-list { @for $i from 1 through $columns { .col-#{$i}-m { @extend %float-styles; } } } @include col-x-list;
This approach generates a comma-separated list of classes with the specified styling:
.col-1-m, .col-2-m, .col-3-m, .col-4-m, .col-5-m, .col-6-m, .col-7-m, .col-8-m, .col-9-m, .col-10-m, .col-11-m, .col-12-m { float: left; }
Reference Materials
The above is the detailed content of How Can I Generate a Comma-Separated List of CSS Classes Dynamically in SCSS?. For more information, please follow other related articles on the PHP Chinese website!