Sass is an extension of the CSS3 language that can help you write better stylesheets with less effort and get more creative with your work. Because you’re quicker to embrace change, you’ll also dare to innovate in your design. You write stylesheets that are comfortable with changing colors or HTML tags, and compile standard CSS code for use in a variety of production environments. Sass syntax is relatively simple, the difficulty lies in how to apply Sass to actual projects, solve the pain points of CSS, so as to improve our efficiency. After exploring practical projects, the following 14 practical experiences are summarized to share, hoping to help everyone broaden their thinking and better apply Sass to practical projects. In the project, we use class-CSS syntax that supports traditional —
Scss, so the following project experience is summarized and shared with Scss as an example.
Scss, so the following project experience is summarized and shared with Scss as an example.
1. Use of variable $
We can use variables to duplicate property values, such as color, border size, image path, etc., so that we can change one place, so that we can make global changes, so as to achieve “skin” function.
Example 1: Our component library, using variable configuration, makes uniform changes to component colors, font sizes, etc. (peels) :
$color-primary: #3ecacb;
$color-success: #4fc48d;
$color-warning: #f3d93f;
$color-danger: #f6588e;
$color-info: #27c6fa; Copy the codeCopy the code
Example 2: Image configuration and global import
The following two problems may exist in the use of images in Scss:
(1) If the style file is not in the same directory as the Vue file using the style file, the image can not be found
(2) If the image path configuration variable is written in the style of the VUE file, but this writing method leads to the separation of the image and the style
We can do this by writing the image path as a configuration file and importing it globally, so that the image path can be changed uniformly (and this method will only load when the corresponding image is used, causing no additional performance issues) :
$common-path: './primary/assets/img/';
$icon-see: $common-path+'icon-see.png';
$icon-play: $common-path+'icon-play.png';
$icon-comment: $common-path+'icon-comment.png';
$icon-checkbox: $common-path+'icon-checkbox.png'; Copy the codeCopy the code
2. @import Imports the Scss file
(1) the @import rule in Css, which allows you to import other Css files in one Css file. The consequence, however, is that the browser will only download additional CSS files when @import is executed, which makes the page load very slow.
(2) the @import rule in Scss. The difference is that the @import rule in Scss imports related files when CSS files are generated. This means that all related styles are grouped into the same CSS file without making additional download requests.
Example 1: The component library uniformly imports the component’s style file into index.sccsThen, if there is a place in the project where the component library is used, just import the index.scss file at the entrance of the project, as shown below.
@import "./base.scss";
@import "./webupload.scss";
@import "./message-hint.scss"; Copy the codeCopy the code
3, the use of local file naming
The file name of an SCSS local file starts with an underscore. This way, SCSS does not compile the file separately at compile time to output CSS, but only uses the file as an import. Mixer mixins are the most appropriate use scenario when using SCSS, because mixers do not need to compile output CSS files separately.
Example 1: Write the mixer name as a local file name, as shown below
4. Scss nesting function and parent selector identifier
We can use nesting and the parent selector identifier & to reduce repetitive code, especially if your CSS class uses the BEM naming convention, where style class naming is verbose. Using this feature, you can solve the problem of long BEM naming, and the style is more readable.
Example 1: Nested functions and parent selector identifiers & Solve BEM verbosity problem:
.tea-assignhw { &__top { margin: 0; } &__content { padding-left: 45px; } &__gradeselect { width: 158px; }} Copy the codeCopy the code
Example 2:Nesting uses child selectors, sibling selectors, and pseudo-class selectors
(1) Child selector
&__hint { margin: 20px; font-size: 14px; > p:first-child { font-weight: bold; }} Copy the codeCopy the code
(2) Sibling selector
&__input { width: 220px; & + span { margin-left: 10px; }} Copy the codeCopy the code
(3) Pseudo-class selector
&__browse {
background: url($btn-search) no-repeat;
&:hover {
background: url($btn-search) -80px 0 no-repeat;
}
&:visited {
background: url($btn-search) -160px 0 no-repeat; }} Copy the codeCopy the code
5. Use of @mixin and @extend directives
Variables allow you to reuse attribute values, but what if you want to reuse a long set of rules? The traditional way to do this is if you’re in a style sheet
The common rules are pulled out and placed in a new CSS class.
You can use the @mixin and @extend inheritance directives in Scss to address the reuse of a large section of rules mentioned above. But what’s the difference between the two scenarios?
(1) The main advantage of @mixin is its ability to accept parameters. If you wanted to pass arguments, you would naturally choose @mixin over @extend, since @extend cannot accept arguments
(2) Because the mixer rules are mixed into other classes, repetition cannot be completely avoided in the output stylesheet. Selector inheritance means that one selector can reuse all the styles of another selector without repeating the output of those style attributes. Use @extend to produce DRY CSS style code (Don’t repeat Yourself)
In summary, if you need to pass parameters, only use @mixin mixers, otherwise it is better to use @extend inheritance.
Example 1: Use of @mixin mixers
@mixin paneactive($image.$level.$vertical) {
background: url($image) no-repeat $level $vertical;
height: 100px;
width: 30px;
position: relative;
top: 50%;
}
&--left-active {
@include paneactive($btn-flip, 0, 0);
}
&--right-active {
@include paneactive($btn-flip, 0, -105px); } Duplicate codeCopy the code
Example 2: Use of the @extend inheritance
.common-mod {
height: 250px;
width: 50%;
background-color: #fff;
text-align: center;
}
&-mod {
@extend .common-mod;
float: right; } &-mod2 { @extend .common-mod; } Duplicate codeCopy the code
6. Use of default parameter values for @mixin mixer
Instead of passing all the parameters in the @include mixer, you can specify a default value for the parameter. If you want to pass a default value for the parameter, you can omit it in the @include mixer. If the required parameter is not the default value, a new parameter is passed to @include.
Example 1: Use of @mixin mixer default parameter values
@mixin pane($dir: left) {
width: 35px;
display: block;
float: $dir;
background-color: #f1f1f1;} &__paneleft { @include pane; } &__paneright { @include pane(right); } Duplicate codeCopy the code
7, #{} interpolation use
Variables can be used in a selector or property name through the #{} interpolation statement. When there are two pages with similar styles, we will extract the similar styles into a page mixer, but the named names of the two different page styles are not the same according to the BEM naming convention, then we can use interpolation for dynamic naming.
Example 1: Class names in a page-level mixer are set dynamically using #{} interpolation
@mixin home-content($class{.#{$class} {
position: relative;
background-color: #fff; overflow-x: hidden; overflow-y: hidden; &--left { margin-left: 160px; } &--noleft { margin-left: 0; }}} copy the codeCopy the code
8. Use of computation
SassScript supports addition, subtraction, multiplication, division, and rounding operations (+, -, *, /, %).
Example 1: The input component sets the left and right inner margins based on the height of the input box, as shown below:
.ps-input {
display: block;
&__inner {
-webkit-appearance: none;
padding-left: #{$--input-height + 10
};
padding-right: #{$--input-height + 10}; }} Copy the codeCopy the code
9. Application of SCSS built-in functions
SCSS comes with some functions, such as HSL and MIX.
Example 1: The clicked color of a button component mixes several colors together in a certain proportion to produce another color.As follows:
&:focus { color: mix($--color-white, $--color-primary, $--button-hover-tint-percent); border-color: transparent; background-color: transparent; } &:active { color: mix($--color-black, $--color-primary, $--button-active-shade-percent); border-color: transparent; background-color: transparent; } Duplicate codeCopy the code
10. Application of SCSS built-in functions
The @for directive can repeat output styles within limits, changing the output each time according to the value of the variable.
Example 1: For example, the project needs to set the styles of 2 to 8 div child nodes under the hwicon class, as follows:
@for $i from 2 through 8 {
.com-hwicon {
> div:nth-child(#{$i}) {
position: relative;
float: right; }}} copy the codeCopy the code
11, each traversal, map data type, @mixin/@include mixer, #{} interpolation combination
Different selector classes can be generated by combining each traversal, map data types, @mixin/@include mixers, and #{} interpolation, with different background images in each selector class, as shown below:
$img-list: (
(accessimg, $papers-access),
(folderimg, $papers-folder),
(bmpimg, $papers-bmp),
(xlsimg, $papers-excel),
(xlsximg, $papers-excel),
(gifimg, $papers-gif),
(jpgimg, $papers-jpg),
(unknownimg, $papers-unknown)
);
@each $label.$value in $img-list {
.com-hwicon__#{$label} {
@include commonImg($value); }} Copy the codeCopy the code
12, style code check — stylelint plug-in
CSS isn’t exactly a programming language, but it’s not something to be sniffed at in a front-end architecture. CSS is a descriptive style sheet, and if the description is chaotic and without rules, it can be a time bomb for other developers, especially the obsessive-compulsive crowd. CSS may seem simple, but writing beautiful CSS is still very difficult. So action is needed to validate CSS rules. Stylelint is a powerful modern CSS detector that lets developers follow consistent conventions and avoid errors in style sheets.
(1) Install gulp, stylelint, gulp-PostSCSS, PostCSS-Reporter, stylelint-config-Standard,The installation command is:
NPM install gulp stylelint gulp-postscss postcss-reporter stylelint-config-standard--save-devCopy the code
(2) Gulpfile. js will be created in the root directory of the project after the installation.
var reporter = require('postcss-reporter');
var stylelint = require('stylelint');
var stylelintConfig = {
'extends': 'stylelint-config-standard'.'rules': {
'at-rule-no-unknown': [
true, {
'ignoreAtRules': [
'extend'.'include'.'mixin'.'for'}]}}; gulp.task('scss-lint'.function() {
var processors = [
stylelint(stylelintConfig),
reporter({
clearMessages: true,
throwError: true})];return gulp.src(
['src/style/*.scss']// The SCSS file that needs the tool to check).pipe(postcss(processors)); }); gulp.task('default'['scss-lint']); Copy the codeCopy the code
(3) Stylelint-config-standard inspection rule
Stylelint-config-standard is the standard check rule officially recommended by stylelint. For details about the check rule, see the official website.
(4) Run the command to check the style, as shown in the figure below
Automatic style repair plugin — Stylefmt plugin
Stylefmt is a stylelint-based code correction tool that formats output for modifiers based on stylelint’s code specification conventions.
(1) The gulp.js configuration file is as follows:
var stylefmt = require('gulp-stylefmt'); // gulp.task('stylefmt'.function() {
return gulp.src(
['src/style/student/index.scss'Pipe (stylefmt(stylelintConfig)).pipe(gulp.dest(stylelintConfig))'src/style/dest/student')); }); gulp.task('fix'['stylefmt']); Copy the codeCopy the code
(2) Run the command to repair the style, as shown in the figure below
Compile SCSS syntax into CSS syntax – gulp-sass plugin
When we first wrote the SCSS code, we were not familiar with the syntax, so the page effect of the SCSS code we wrote was not what we wanted. In this case, we can use gulp-sass plug-in to listen to SCSS code and generate CSS code in real time, so that we can judge whether the SCSS code written is correct by viewing the CSS code.
(1) The gulp.js configuration file is as follows:
var gulpsass = require('gulp-sass');
gulp.task('gulpsass'.function() {
return gulp.src('src/style/components/hwIcon.scss')
.pipe(gulpsass().on('error', gulpsass.logError))
.pipe(gulp.dest('src/style/dest')); }); gulp.task('watch'.function() {
gulp.watch('src/style/components/hwIcon.scss'['gulpsass']); }); Copy the codeCopy the code
(2) Run commands to listen to SCSS files and dynamically compile SCSS code to generate CSS code files, as shown in the following figure
The above is the summary of 14 SCSS actual combat experience to share, I hope you have some reference, if you have inspiration, please like and encourage, if you have any questions or suggestions, welcome to leave a comment and discuss.