How To Use SCSS In Laravel

How To Use SCSS In Laravel

SCSS (Sassy CSS) is a powerful extension of CSS that provides enhanced features like variables, nested rules, and mixins. These features help developers write more efficient and maintainable stylesheets. Laravel, a popular PHP framework, integrates easily with SCSS through its built-in Laravel Mix tool, simplifying the process of compiling SCSS into CSS. In this guide, you will learn how to use SCSS in Laravel project, from setup to advanced techniques, ensuring an optimized workflow for modern web development.

Table of Contents

What is SCSS and Why Use It in Laravel?

SCSS is a syntax of the preprocessor SASS (Syntactically Awesome Style Sheets). It extends regular CSS with features such as variables, nesting, and functions, which allow developers to write clean, scalable code. Unlike traditional CSS, SCSS improves code reusability and maintainability by allowing you to use variables for colors, fonts, and other properties that may change across your project. This reduces redundancy and makes it easier to update styles globally.

In Laravel, SCSS is compiled into standard CSS using Laravel Mix. Mix is a configuration layer built on top of Webpack that simplifies the asset compilation process. By leveraging SCSS in Laravel, you can create more organized and modular styles, streamlining the front-end development process.

Configuring SCSS in Laravel

Installing Laravel Mix

Laravel Mix is pre-installed with new Laravel projects, but you need Node.js and NPM (Node Package Manager) to use it. If they are not installed, follow these steps:

1. Install Node.js and NPM

Download the latest stable version of Node.js from nodejs.org.

2. Verify Installation

Open your terminal and run
				
					node -v
npm -v

				
			

3. Install Laravel Mix

If you are starting a new Laravel project, run
				
					composer create-project --prefer-dist laravel/laravel scss-laravel

				
			
Navigate into your project directory and run:
				
					npm install

				
			

Configuring Laravel Mix for SCSS

After installing Mix, you need to configure it to compile SCSS into CSS. The configuration is done in the webpack.mix.js file located in the root of your Laravel project.

1. Open the webpack.mix.js file and modify it as follows:

				
					mix.sass('resources/scss/app.scss', 'public/css');

				
			
This command tells Laravel Mix to compile the app.scss file located in the resources/scss folder and output the resulting CSS file into the public/css directory.

After modifying the file, run the following command to compile your SCSS

				
					npm run dev

				
			
The compiled CSS file will be generated in the public/css directory, and you can link it in your Blade templates.

Creating and Organizing SCSS Files in Laravel

A well-organized SCSS file structure is crucial for maintainability in large projects. Here is a recommended folder structure for SCSS files in a Laravel project:
				
					resources/scss/
    base/
        _reset.scss
        _typography.scss
    components/
        _buttons.scss
        _forms.scss
    layouts/
        _header.scss
        _footer.scss
    app.scss

				
			
  1. Base folder: Contains foundational styles like resets and typography.
  2. Components folder: Contains styles for UI components like buttons, forms, and cards.
  3. Layouts folder: Contains styles for page layouts, headers, and footers.

Use the @import directive to modularize SCSS code. For example, in app.scss:
				
					@import 'base/reset';
@import 'base/typography';
@import 'components/buttons';
@import 'layouts/header';

				
			
This approach keeps your SCSS code modular, organized, and easy to maintain.

Compiling and Testing SCSS in Laravel

After organizing your SCSS files, you need to compile them using Laravel Mix. Compilation can be done in two modes: development and production.

1. Development Mode

Run the following command for unminified output, which is easier to debug:
				
					npm run dev
				
			
This command compiles the SCSS and outputs a readable CSS file.

2. Production Mode

For optimized, minified CSS suitable for production, run:
				
					npm run production

				
			
The output CSS will be smaller and optimized for faster loading times.
				
					composer create-project --prefer-dist laravel/laravel scss-laravel

				
			
After compiling, you can include the compiled CSS file in your Blade templates:
				
					<link rel="stylesheet" href="{{ asset('css/app.css') }}">

				
			
Test the styles in the browser to ensure that everything is working as expected.

Advanced SCSS Techniques in Laravel

Variables, Mixins, and Functions

SCSS allows you to use variables, mixins, and functions to make your styles more reusable and maintainable. Here’s how you can use these features:

1. Variables

				
					$primary-color: #3490dc;
$font-stack: Helvetica, sans-serif;

body {
    font-family: $font-stack;
    color: $primary-color;
}

				
			

2. Mixins

Mixins allow you to reuse blocks of code across different selectors.
				
					@mixin border-radius($radius) {
    border-radius: $radius;
}

.button {
    @include border-radius(5px);
}

				
			

3. Functions

Functions allow you to perform calculations and return values.
				
					@function double($n) {
    @return $n * 2;
}

.box {
    width: double(10px);
}

				
			

SCSS Nesting and Inheritance

Nesting allows you to structure your CSS in a way that mirrors your HTML. Here’s an example:
				
					nav {
   ul {
       margin: 0;
       padding: 0;
       list-style: none;
   }

   li { 
       display: inline-block; 
   }

   a {
       text-decoration: none;
   }
}

				
			
Nesting makes your styles more readable and easier to manage. However, avoid deep nesting, as it can make the compiled CSS harder to maintain.

Conditional Statements and Loops

SCSS also allows the use of conditional statements and loops, which can be useful for generating repetitive styles dynamically.

1. Conditional Statements

				
					$theme: dark;

body {
    @if $theme == light {
        background-color: #fff;
    } @else {
        background-color: #333;
    }
}

				
			

2. Loops

Mixins allow you to reuse blocks of code across different selectors.
				
					@for $i from 1 through 5 {
    .column-#{$i} {
        width: (100% / $i);
    }
}

				
			

3. Functions

Functions allow you to perform calculations and return values.
				
					@function double($n) {
    @return $n * 2;
}

.box {
    width: double(10px);
}

				
			

Deploying SCSS in Production with Laravel

When deploying your Laravel project, you should compile your SCSS for production using the npm run production command. This will create minified CSS files optimized for performance. Laravel Mix also handles versioning and cache-busting for your compiled CSS, ensuring that users get the latest styles when you update them.

To enable versioning, add the following to your webpack.mix.js file:

				
					mix.sass('resources/scss/app.scss', 'public/css').version();

				
			
In your Blade templates, reference the versioned file:
				
					<link rel="stylesheet" href="{{ mix('css/app.css') }}">

				
			
This will ensure that your CSS files are properly cached and updated when changes are made.

Common SCSS and Laravel Issues and How to Solve Them

  • SCSS Compilation Errors: Ensure that your webpack.mix.js is configured correctly and that the sass-loader is installed. If you encounter errors, re-run npm install to make sure all dependencies are installed.

  • CSS Not Updating: This issue is often caused by browser caching. Clear the cache or use versioning in Laravel Mix to force the browser to load the latest version of the CSS file.

  • Laravel Mix Not Compiling SCSS: Make sure you are running the correct npm commands (npm run dev or npm run production) and that Node.js and NPM are correctly installed.

Final Words

Integrating SCSS into Laravel projects significantly enhances front-end development by providing advanced features for writing maintainable and scalable CSS. By using Laravel Mix, you can easily compile and optimize your SCSS for both development and production environments. Following best practices for organizing SCSS files, using variables, mixins, and functions will help you write clean and efficient stylesheets.

Written By,

Picture of Md Monayem Islam

Md Monayem Islam

Hey, I'm Md Monayem Islam. I’m a Full Stack Developer with extensive expertise in Laravel (PHP), Vue.js (TypeScript), and API development. Over the years, I’ve honed my skills in building dynamic and scalable web applications. Previously, I worked on a variety of projects, creating robust solutions and enhancing the user experience for clients worldwide. Now, I’m here to share my knowledge and help you develop web applications.

Want a FREE Consultation?

I am here to assist with your queries. Schedule now!
Share the Post:

Let's Connect!

Have a question? Contact me and I’ll get back to you soon.

Do you Need a developer for your project?