CSS Preprocessors

CSS Preprocessors

(THIS BLOG IS STILL IN PROGRESS)

Refs

  1. Sass
  2. Less
  3. Stylus
  4. PostCss
  5. CSS Preprocessors: What? Why?…How?!

What and why

  • A CSS preprocessor is a program that lets you generate CSS from the preprocessor’s own unique syntax.
  • A CSS preprocessor provides you with a lot of features to make writing css easier, like variables, mixins, nesting, control flow and so on.
  • Most popular css preprocessors include: Sass, Less, Stylus and PostCss.

Features

Variables

1
2
3
4
5
6
7
/* sass */
$primary-color: #333;


body {
color: $primary-color;
}

Nesting

1
2
3
4
5
6
/* sass */
nav {
ul {
margin: 0;
}
}

Mixins

  • A mixin lets you make groups of css declarations you want to reuse, keeping your Sass DRY.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* sass, supports variables in mixin */
@mixin theme($theme: DarkGray) {
background: $theme;
box-shadow: 0 0 1px rgba($theme, 25);
color: #fff;
}

.info {
@include theme;
}
.alert {
@include theme($theme: DarkRed)
}

Extends

  • In Sass, @extend lets you share a set of CSS properties from one selector to another.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/* sass */
/* This CSS will print because %message-shared is extended. */
%message-shared {
border: 1px solid #ccc;
padding: 10px;
color: #333;
}

/* This CSS won't print because %equal-heights is never extended. */
%equal-heights {
display: flex;
flex-wrap: wrap;
}

.message {
@extend %message-shared;
}

.success {
@extend %message-shared;
border-color: green;
}

If/Else

1
2
3
4
5
6
7
8
9
10
11
12
13
/* sass */
@mixin avatar($size, $circle: false) {
width: $size;
height: $size;

@if $circle {
border-radius: $size / 2;
} @else if $size > 10 {
border-radius: $size / 5;
} @else {
border-radius: $size / 10;
}
}

Loops

1
2
3
4
5
6
/* sass */
@for $i from 1 through 3 {
ul:nth-child(3n + #{$i}) {
background-color: lighten($base-color, $i * 5%);
}
}

Imports

1
2
3
4
5
6
7
8
9
10
/* sass */
/* foundation/_code.scss */
code {
padding: .25em;
line-height: 0;
}
/* style.scss */
@import 'foundation/code'
/* As a convention, Sass files that are only meant to be imported, not compiled on their own, begin with _ (as in _code.scss). These are called partials, and they tell Sass tools not to try to compile those files on their own. You can leave off the _ when importing a partial. */

Math

1
2
/* sass (@debug prints value of the expression) */
@debug math.$e; // 2.7182818285
Author

Chendongtian

Posted on

2022-08-30

Updated on

2023-08-04

Licensed under

Comments