Как работать с scss в wordpress?
Всем привет! Работаю с темой в wordpress, где весь каскад прописан в .scss файлах. Работаю через ftp с редактором brackets, и не очень понимают как работать с scss. До этого не пользовался препроцессорами, но там ничего сложного, вот только когда я сохраняю изменения в файле .scss, то ничего не происходит, разумеется, потому что его надо потом компилировать. Так вот вопрос: как это делается и какую тулзу надо использовать в brackets, чтобы работать с .scss через ftp?
- Вопрос задан более трёх лет назад
- 1989 просмотров
Sass in WordPress: A Step-By-Step Guide
In this blog article, we will learn about How to use Sass in WordPress for new users and beginners.
The reality is that Sass (and other CSS preprocessors) can be an extremely powerful ally for any designer or developer interested in writing less and doing more. Eventually, all these preprocessing languages get compiled into CSS.
SCSS provides a bunch of advanced features. You can minify code by using variables which is a huge advantage over traditional CSS. It includes all the features of CSS and even those which are not present in CSS.
Prerequisites
This tutorial assumes that you have a working knowledge of setting up a WordPress environment.
Getting Started
We all know that CSS is a very simple language, very easy to understand but it can be hectic if it’s becoming very long. For eg, If you need to tweak a certain color value for a certain element throughout the whole site, you have to find all CSS for that element from the whole CSS file, then you will replace the value for all CSS. So it can be a nightmare.
Start your headless eCommerce
now. Find out More
So one of the best options to get rid of this hectic job is to use sass, a CSS Preprocessor which allows us to write functions to generate blocks of repeated style code. SASS helps us to write CSS faster and more efficiently. It also helps to increase readability. SASS lets you use features that don’t exist in CSS yet like variables, nesting, mixins, inheritance, etc.
If you are moving an old CSS project into SASS, you will break the huge stylesheet into organized modules. You will set up SASS partials, use variables, and set up a mixing which makes your job easier. Follow the process I mentioned below:
Using SASS compiler
There are a number of ways (application)you can compile your SASS to CSS in which some of which are paid apps and some of them are free. It depends on which 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 start 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 the 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 first 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 gulp before 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
- npm init command will create a package.json file
- After the Creation of package.json, you need to setup 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 folder which 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/$/public_html/wp-content/themes/$/` >, // 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
# JavaSript 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 need never 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 Sass makes your work easier. We’ll discuss each feature in more detail below:
Variables in Sass
One of the most important features of Sass in WordPress is that it allows you to use variables. It lets you define a value and store it in a variable for later use in your style files. Although it is a simple tool, having it at your disposal greatly facilitates your workflow.
So, let’s say you want to use the same color or 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
As you see, with Sass, you can define the $backgroud-color and $primary-color variables at the beginning and then use the variables throughout your code. For example, if you are doing a project where you must use brand colors in every other line of code, then using a variable will make your work easier as you will not have to type the value stored in it every time, Like in css.
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 selector 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
This underscore tells Sass that the file is a part of a larger file and should not be turned into a separate CSS file. You can use the partial Sass files using the @import or @use rule. Here’s a more detailed explanation of how the @import rule works.
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 Sass file as a module. That is you can refer to its variables, functions and mixins in your sass files with the help of namespace which is based on the name of your file. The file you use will also include the generated CSS in your output file.
//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
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
Another useful feature in SaaS are mixins. There are a lot of aspects to CSS that make code writing a bit tedious. A mixin helps you avoid this by creating a set of CSS declarations that you can later reuse throughout your coding. There is also the ability to pass in certain values to make your mixin even more flexible. An example when the use of a mixin is appropriate is vendor prefixes. Let us take the example of change.
// Sass @mixin transform($property) < -webkit-transform: $property; -ms-transform: $property; transform: $property; >.box < @include transform(rotate(30deg)); >// CSS .box
In order to create a mixin, you should use the @mixin directive and then name it. In this example our mixin is named transform. There is also the $property variable which is inside the parentheses to let us pass in a transform or basically anything else we want.
Once your mixin is created, you can use it as a CSS declaration which 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
The last feature in our list is the operators. Sometimes it’s very helpful to do the math in your CSS, and that’s why this Sass feature adds a number of useful math operators, such as +,-,*,/ and %. In the example below you’ll find some simple math calculations to find the width for aside & article.
// 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»]
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 are still new to Sass I encourage you to give it a try. Check out the guide at http://sass-lang.com/ to get a crash course in understanding the language. If you can write CSS, you can write Saas.
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’s more efficiently than ever before.
Add Custom CSS
While most changes can be made with settings in the WordPress editor, you may prefer to use CSS to customize your site if you have experience writing CSS code. This guide will show you how to edit your website with CSS.
This feature is available on sites with our WordPress.com Premium, Business, and Commerce plans. If your site has one of our legacy plans, it is available on the Pro plan.
- About CSS
- Access the CSS Editor via Styles
- Add CSS to Specific Block Types
- CSS Revisions in the Customizer
- Media Width
- Start Fresh
- Preprocessor
- Can I remove the WordPress.com footer credit with CSS?
- Can I remove the black admin bar with CSS?
- Can I use CSS rules like @import and @font-face?
- Can I use web fonts in CSS?
- Can I upload images for use with my CSS?
- Can I edit the CSS stylesheet directly?
- What happens if I cancel my WordPress.com plan?
About CSS
CSS stands for Cascading Style Sheets. It is a markup language that controls the appearance of HTML elements on a web page. WordPress includes a CSS editor to add your own CSS styles to override the default styles of your theme.
There is almost endless potential for what you can do with CSS to modify the design of a website. However, it requires knowledge of how CSS and HTML work (or at least a willingness to learn.) The CSS guide from MDN web docs is a great place to start learning CSS.
If you’re not interested in learning CSS, choose a block theme for your site. These themes provide the most flexible options to customize any aspect of your website’s design without any knowledge of computer code.
There are two methods to access your site’s CSS editor, depending on your theme. Each method is explained below.
Access the CSS Editor via Styles
If your site uses a theme that supports the site editor, you can customize the site with CSS using this method. A quick way to determine if your site uses the site editor is to check under Appearance in your dashboard. If you see Editor here, you can access the CSS editor by following these steps:
- Click the three dots to the right of the “Styles” heading and choose “Additional CSS“:

- Type or paste your CSS into the text box provided.
- Click the “Save” button at the top right of the screen to save the CSS to your site.
You can preview the impact of your CSS changes on any block type by loading the Style Book. Click on the eye icon to open the style book.

Add CSS to Specific Block Types
In Site Editor themes, you can apply CSS code to specific blocks site-wide by following the steps below.

CSS Revisions in the Customizer
The latest 25 versions of your CSS edits are saved and can be accessed by clicking “See full history” at the bottom of the CSS editor. You can restore previous versions of your CSS here.
If the option does not appear, there is no CSS history to restore.

Media Width
The “Media Width” option should be used if you have modified the width of the primary content area using custom CSS. The “Media Width” setting is the default size for full-size images when inserted into your site.
Note that it will not affect the size of some images you added before changing the setting, depending on how they were inserted, and you may have to re-insert some of them after changing the setting.
Start Fresh
By default, the custom CSS you add to the CSS editor will be loaded after the theme’s original CSS, which means that your rules can take precedence and override the theme’s styles.
You can turn the theme’s original CSS off entirely by clicking the “Don’t use the theme’s original CSS” checkbox. This will allow you to use any WordPress.com theme as a blank canvas for designing with CSS. This is an advanced option and should only be used if you want to start over and design the CSS for your theme from scratch.
If you want to build on top of the existing CSS rules—the most common and recommended approach—then you can leave this option disabled.
Preprocessor
WordPress.com has support for CSS preprocessors LESS and Sass (SCSS Syntax). This is an advanced option for users who wish to use CSS extensions like variables and mixins. See the LESS and Sass websites for more information.
Frequently Asked Questions
Can I remove the WordPress.com footer credit with CSS?
All WordPress.com users can choose among several options for the footer credit, from a minimalist WordPress.com logo to text options like “Website Built with WordPress.com”. The footer credit can be hidden on eligible plans.
The footer credit should not be removed with CSS. However, modifying the style of the footer text (i.e., colors and font size) is fine as long as it’s still readable. Using CSS, you can also add content like a copyright notice to the existing footer.
Can I remove the black admin bar with CSS?
All WordPress.com users must maintain the Admin Bar (the dark bar that appears at the top of WordPress.com sites when logged in). If required, customers on plugin-enabled sites can contact support to help remove the Admin Bar.
Can I use CSS rules like @import and @font-face?
Can I use web fonts in CSS?
You can choose your website fonts using the options with your theme. When working with CSS, you are limited to those two web fonts on the front end. However, you can add additional fonts using third-party font plugins.
Can I upload images for use with my CSS?
Yes. You can upload an image to your Media Library and refer to it by its direct URL from within your CSS stylesheet. Here’s an example of how to use a background image in your stylesheet:
div#content < background-image: url('http://example.files.wordpress.com/1999/09/example.jpg'); >Can I edit the CSS stylesheet directly?
We recommend making CSS edits using the CSS editor, as explained in this guide above. When you add CSS using this method, it overrides CSS rules from your theme’s stylesheet. This is a safe method that makes it easier to debug CSS conflicts and restore previous versions of CSS you’ve added.
If you are proficient in editing theme files directly, you can do so via SFTP or by creating a child theme. We recommend testing changes on a staging site before applying them to your live site.
What happens if I cancel my WordPress.com plan?
All upgrades on WordPress.com are renewed yearly. Should you cancel your subscription, your custom CSS will still be saved, but it will no longer be applied to your site for others to see. If you would like them re-applied to your site, you can repurchase your plan, and the styles will be re-applied automatically, provided you haven’t changed themes. If you have changed themes, you will find your past CSS in the CSS revisions.
Was this guide helpful for you?
