Sass in WordPress: A Step-By-Step Guide
In this blog article, we will learn how to use Sass in WordPress for new users and beginners.
Sass and other CSS preprocessors are powerful tools that help designers and developers write less code while achieving more. In the end, all preprocessed code is compiled into standard CSS.
SCSS offers advanced features like variables for cleaner, more maintainable, and minified code. It supports all CSS capabilities and adds powerful features that go beyond traditional CSS.
Prerequisites
This tutorial assumes that you have a working knowledge of setting up a WordPress environment.
Getting Started
CSS is easy to learn, but large stylesheets can become hard to manage.
Changing a single value, like a color across the site, often means finding and updating it everywhere, which can quickly turn into a nightmare.
Sass, a CSS preprocessor, removes repetitive work by generating reusable style blocks.
It speeds up development, improves readability, and adds features like variables, nesting, mixins, and inheritance.
When migrating an old CSS project to Sass, you can split large stylesheets into clean, organized modules. Using partials, variables, and mixins makes the code easier to manage and maintain.
Follow the process I mentioned below:
Using the SASS compiler
There are a number of ways (applications)you can compile your SASS to CSS, some of which are paid apps and some of which are free. It depends on which one you want to use. Some paid app includes
- CodeKit (Paid) Mac
- Hammer (Paid) Mac
- LiveReload (Paid, Open Source) Mac Windows
- Prepros (Paid) Mac Windows Linux
- Scout-App (Free, Open Source) Windows Linux Mac
Others include using grunt, gulp. I prefer using gulp. Here is the link where you can find all the details about how to get started with a gulp.
What is Gulp?
gulp is a toolkit for automating painful or time-consuming tasks in your development workflow, so you can stop messing around and build something.
This perfectly describes what Gulp really is. Install it in a few easy steps:
- Install Node.js.
- Install Gulp globally: npm install gulp-cli -g
- Make a theme folder with: mkdir themeName and enter the folder with cd themeName.
- Initialize your project with npm: npm init
Install Node.js
Gulp requires you to download and install Node.js, which will also install NPM, which is its package manager, and it is used to install modules.
To verify that you have installed Node.js and NPM correctly, open the terminal and check their current version by entering the commands: node -v and npm -v.
Install Gulp globally
- If you’ve previously installed gulp globally, run
npm rm --global gulpbefore following these instructions. - Install the gulp command line utility, run: npm install –global gulp-cli.
Initialize Gulp In Project Directory
- Create a theme folder in wp-content/theme
- Use the npm init command for initialization. The
- npm init command will create a package.json file
- After the Creation of package.json, you need to set up the gulp dependencies
# Setup Gulp Dependencies
run the following npm command to install Gulp and all plug-ins as development dependencies:
npm install --save-dev autoprefixer browser-sync css-mqpacker cssnano gulp-concat gulp-deporder gulp-imagemin gulp-newer gulp-postcss gulp-sass gulp-strip-debug gulp-uglify gulp-noop postcss-assets
This will create a node_modules A folder that contains the module code with dependencies. For Git users, add node_modules to your .gitignore file.
# Create Gulp Configuration File
Create a new gulpfile.js the configuration file in your project folder
edit the file gulpfile.js in your project source folder, replace its content, if any, with these contents:
// Gulp.js configuration
'use strict';
const
// ** change these two to yours **
wordpress_project_name = 'your-site',
theme_name = 'your-site',
browserSyncProxy = 'http://local.your-site.test/',
// source and build folders, ** change this to yours **
dir = {
src : 'src/',
build : `../../vagrant-local/www/${wordpress_project_name}/public_html/wp-content/themes/${theme_name}/`
},
// Gulp and plugins
{ src, dest, series, parallel, watch } = require('gulp'),
noop = require("gulp-noop"),
newer = require('gulp-newer'),
imagemin = require('gulp-imagemin'),
sass = require('gulp-sass'),
postcss = require('gulp-postcss'),
deporder = require('gulp-deporder'),
concat = require('gulp-concat'),
stripdebug = require('gulp-strip-debug'),
uglify = require('gulp-uglify'),
browserSync = require('browser-sync').create(),
log = require('fancy-log')
;
// For BrowserSync
const reload = (cb) => { browserSync.reload(); cb(); };
#Image Processing
Image files can often be compressed further using tools such as imagemin. Add the following code to gulpfile.js:
// image settings
const images = {
src : dir.src + 'images/**/*',
build : dir.build + 'images/'
};
// image processing
gulp.task('images', () => {
return gulp.src(images.src)
.pipe(newer(images.build))
.pipe(imagemin())
.pipe(gulp.dest(images.build));
});
Save then run gulp images
# Sass Compilation
WordPress cannot use Sass files directly; you must compile to a single style.css file. Add the following code to gulpfile.js
// CSS settings
var css = {
src : dir.src + 'scss/style.scss',
watch : dir.src + 'scss/**/*',
build : dir.build,
sassOpts: {
outputStyle : 'nested',
imagePath : images.build,
precision : 3,
errLogToConsole : true
},
processors: [
require('postcss-assets')({
loadPaths: ['images/'],
basePath: dir.build,
baseUrl: '/wp-content/themes/wptheme/'
}),
require('autoprefixer')({
browsers: ['last 2 versions', '> 2%']
}),
require('css-mqpacker'),
require('cssnano')
]
};
// CSS processing
gulp.task('css', ['images'], () => {
return gulp.src(css.src)
.pipe(sass(css.sassOpts))
.pipe(postcss(css.processors))
.pipe(gulp.dest(css.build))
.pipe(browsersync ? browsersync.reload({ stream: true }) : gutil.noop());
});
Launch this new task with gulp css
# JavaScript Processing
Add the following code to gulpfile.js:
// JavaScript settings
const js = {
src : dir.src + 'js/**/*',
build : dir.build + 'js/',
filename : 'scripts.js'
};
// JavaScript processing
gulp.task('js', () => {
return gulp.src(js.src)
.pipe(deporder())
.pipe(concat(js.filename))
.pipe(stripdebug())
.pipe(uglify())
.pipe(gulp.dest(js.build))
.pipe(browsersync ? browsersync.reload({ stream: true }) : gutil.noop());
});
Run this new task with gulp js
# Run Everything
Rather than calling each task separately, we can add the following code to gulpfile.js:
// run all tasks
gulp.task('build', ['css', 'js']);
You can now use gulp build to run the js, css and images tasks in parallel. (Note images is a dependency of the css task, as we set it up early, so we need not call it directly.)
# Enable File Watching And Browsersync
Your workflow can be radically improved by:
- Letting Gulp watch for file changes before launching the appropriate task.
- Automatically reloading CSS and JavaScript files when they change (without a page refresh).
- Automatically refreshing the page when a template file changes.
First, we need to define a browsersync task in gulpfile.js.
This will create a proxy server to your web server running WordPress on localhost (Change this domain or use an IP address as necessary):
// Browsersync options
const syncOpts = {
proxy : 'localhost',
files : dir.build + '**/*',
open : false,
notify : false,
ghostMode : false,
ui: {
port: 8001
}
};
// browser-sync
gulp.task('browsersync', () => {
if (browsersync === false) {
browsersync = require('browser-sync').create();
browsersync.init(syncOpts);
}
});
Now add a watch The task to run Browsersync, watch for file changes, and run the appropriate task:
// watch for file changes
gulp.task('watch', ['browsersync'], () => {
// image changes
gulp.watch(images.src, ['images']);
// CSS changes
gulp.watch(css.watch, ['css']);
// JavaScript main changes
gulp.watch(js.src, ['js']);
});
Finally, add a default Gulp task, which runs an initial build and starts the watch task:
// default task
gulp.task('default', ['build', 'watch']);
Now run gulp from the command line. The console will display output which includes lines similar to:
[BS] Proxying: http://localhost
[BS] Access URLs:
-------------------------------------
Local: http://localhost:3000
External: http://192.168.15.194/:3000
-------------------------------------
UI: http://localhost:8001
UI External: http://192.168.15.194/:8001
-------------------------------------
[BS] Watching files...
Your WordPress site will load as before, but Gulp will watch for changes and apply the updates immediately. You’ll never need to switch to your browser and click refresh again!
Let’s write some Sass
Now that we are all configured, we are ready to write some Sass.
Prerequisites in Sass
- Basic understanding of HTML & CSS
- A code editor (VS Code recommended). If you don’t have it installed, download it here.
- And a browser (Chrome or Firefox recommended)
What exactly is Sass?
Sass (Syntactically Awesome Style Sheets) is a CSS preprocessor that gives your CSS superpowers.
What additions does SASS bring to CSS?
These are the features Sass adds to CSS to make your work easier:
- Variables
- Nested rules
- Partials
- Modules
- Mixins
- Extends/inheritance
- Operators
These are the additions through which makes your work easier. We’ll discuss each feature in more detail below:
Variables in Sass
One key Sass feature in WordPress is variables, letting you define and reuse values across stylesheets. This simple tool greatly improves consistency and speeds up your overall workflow.
So, let’s say you want to use the same color, font, or any other CSS value throughout your coding.
Just store it in a variable and reuse it whenever you want. Remember that SASS uses the $symbol for variables.
Here’s an example of variable usage in Sass vs CSS:
// CSS
body {
background: #ccc;
color: #333;
}
// SCSS
$backgroud-color:#ccc;
$primary-color: #333;
body {
background: $backgroud-color;
color: $primary-color;
}
With Sass, you define variables like $background-color and $primary-color Once and reuse them everywhere.
This is especially useful for brand colors, saving time and avoiding repetitive value updates.
Nested rules in Sass
Sass also comes in handy when you need to make your code more readable. With Sass, you can nest your CSS selectors in the same way as you can in HTML.
Here’s an example of nesting used in SASS:
// CSS
nav ul {
margin: 0;
padding: 0;
list-style: none;
}
nav li {
display: inline-block;
}
nav a {
display: block;
padding: 6px 12px;
text-decoration: none;
}
// SCSS
nav {
ul {
margin: 0;
padding: 0;
list-style: none;
}
li { display: inline-block; }
a {
display: block;
padding: 6px 12px;
text-decoration: none;
}
}
As you can see, the ul, li, and a selectors are nested inside the nav selector, which makes your CSS code more organized, cleaner, and easier to read.
Partials in Sass
You have the ability to create partial Sass files that have small snippets of CSS that you can later include in other Sass files.
You can use the partial Sass file by using the underscore _partial.css in the name of your file
The underscore tells Sass the file is a partial and shouldn’t compile into its own CSS file. These partials are included using the @import or @use rules.
sass/ | |– abstracts/ | |– _variables.scss # Sass Variables | |– _functions.scss # Sass Functions | |– _mixins.scss # Sass Mixins | |– _placeholders.scss # Sass Placeholders | |– base/ | |– _reset.scss # Reset/normalize | |– _typography.scss # Typography rules | … # Etc. | |– components/ | |– _buttons.scss # Buttons | |– _carousel.scss # Carousel | |– _cover.scss # Cover | |– _dropdown.scss # Dropdown | … # Etc. | |– layout/ | |– _navigation.scss # Navigation | |– _grid.scss # Grid system | |– _header.scss # Header | |– _footer.scss # Footer | |– _sidebar.scss # Sidebar | |– _forms.scss # Forms | … # Etc. | |– pages/ | |– _home.scss # Home specific styles | |– _contact.scss # Contact specific styles | … # Etc. | |– themes/ | |– _theme.scss # Default theme | |– _admin.scss # Admin theme | … # Etc. | `– main.scss # Main Sass file
Modules in Sass
Now, when you split your Sass into separate parts with the @use rule, it will start loading the file as a module.
That is, you can refer to its variables, functions, and mixins in your files using a namespace based on your file’s name. The file you use will also include the generated CSS in its output.
//Sass
// _base.scss
$background-color: #ddd;
$primary-color: #333;
body {
background: $background-color;
color: $primary-color;
}
// styles.scss
@use 'base';
.inverse {
background-color: base.$primary-color;
color: white;
}
// CSS
body {
font: 100% Helvetica, sans-serif;
color: #333;
}
.inverse {
background-color: #333;
color: white;
}
As you can see, this makes your workflow more organized as you can define variables in separate files and then import them into a different Sass file.
Mixins in Sass
Mixins are a powerful Sass feature that reduces repetitive CSS by letting you reuse groups of declarations.
They also accept values for flexibility, making them ideal for tasks like handling vendor prefixes.
// Sass
@mixin transform($property) {
-webkit-transform: $property;
-ms-transform: $property;
transform: $property;
}
.box { @include transform(rotate(30deg)); }
// CSS
.box {
-webkit-transform: rotate(30deg);
-ms-transform: rotate(30deg);
transform: rotate(30deg);
}
To create a mixin, use the @mixin directive and give it a name, such as transform.
You can pass values using variables like $property, allowing the mixin to handle transforms or any other input flexibly.
Once your mixin is created, you can use it as a CSS declaration that starts with @include and then is followed by the name of the mixin.
Extends/Inheritance in Sass
Finally, one of the most useful features of Sass is the @extend. This feature helps you share a group of CSS properties of one selector with another.
Operators in Sass
Operators in Sass let you perform math directly in your stylesheets using +, -, *, /, and %. This makes tasks like calculating widths for elements such as aside and article simple and efficient.
// SCSS SYNTAX
.container {
width: 100%;
}
article[role="main"] {
float: left;
width: 600px / 960px * 100%;
}
aside[role="complementary"] {
float: right;
width: 300px / 960px * 100%;
}
// CSS OUTPUT
.container {
width: 100%;
}
article[role="main"] {
float: left;
width: 62.5%;
}
aside[role="complementary"] {
float: right;
width: 31.25%;
}
In this example, we’ve made a simple fluid grid which is based on 960 px. With operations in Sass, we convert pixel values to percentages without too much of a hassle.
Conclusion
If you’re new to This, give it a try and explore the guide at Sass Doc for a quick start. If you can write CSS, you already have the skills to write Sass.
Hopefully, this tutorial brings anyone using Sass a better understanding of how to combine it with WordPress and helps you build or edit your theme more efficiently than ever before.