What are differences between mixins, extend and placeholders in Sass

What are differences between mixins, extend and placeholders in Sass

In this SCSS, SASS tutorial, we will explore how to use mixins, extend and placeholders and the difference between it.

Stylesheet development with SASS/SCSS, even when using its most basic features, like nesting properties or variables, saves valuable time and makes life easier for front-end developers. It’s not surprising that CSS pre-processors have been widely adopted as the de facto way of creating styles for websites and applications.

In this SASS/SCSS tutorial, we will explore how to use @mixins, @extend and placeholders and the difference between it.

How to use @mixins in SASS/SCSS

Some things in CSS are a bit tedious to write, especially with CSS3 and the many vendor prefixes that exist. A mixin lets you make groups of CSS declarations that you want to reuse throughout your site. You can even pass in values to make your mixin more flexible. A good use of a mixin is for vendor prefixes.

To create a mixin you use the @mixin directive and give it a name. We've named our mixin size. We're also using the variable $width, $height inside the parentheses so we can pass in a transform of whatever we want. After you create your mixin, you can then use it as a CSS declaration starting with @include followed by the name of the mixin.

@mixin size($width: 100%, $height: 100%) {
  width: $width;
  height: $height;  
}

.img-fluid{
	@include size();
}

.avatar{
	@include size(50px, 50px);
}

.avatar-lg{
	@include size(60px, 60px);
}

Here is the result after compilation:

.img-fluid{
	width: 100%;
	height: 100%;
}

.avatar{
	width: 50px;
	height: 50px;
}

.avatar-lg{
	width: 60px;
	height: 60px;
}

How to use @extend in SASS/SCSS

.avatar-status {
  &:before {
    content: '';
    position: absolute;
    bottom: 5%;
    right: 5%;
    width: 20%;
    height: 20%;
    border-radius: 50rem;
    border: 1px solid #fff;
  }
}

.avatar-online {
  @extend .avatar-status;
  &:before {
    background-color: green;
  }
}

.avatar-busy {
  @extend .avatar-status;
  &:before {
    background-color: red;
  }
}

in the CSS the result is:

.avatar-status:before, .avatar-online:before, .avatar-busy:before {
    content: '';
    position: absolute;
    bottom: 5%;
    right: 5%;
    width: 20%;
    height: 20%;
    border-radius: 50rem;
    border: 1px solid #fff;
}

.avatar-online:before {
    background-color: green;
}

.avatar-busy:before {
    background-color: red;
}

This is one of the most useful features of Sass. Using @extend lets you share a set of CSS properties from one selector to another. It helps keep your Sass very DRY. With @extend, you can't pass parameters during the extending, but that's not the idea actually. @extend should be used in those places where you want to share properties between the elements.

The final code is still not perfect. That's because the .avatar-status class is also written in our final .css file. You may not use it at all, so it will be good if it is hidden. To achieve this you could use placeholders.

How to use placeholders in SASS/SCSS

%avatar-status {
  &:before {
    content: '';
    position: absolute;
    bottom: 5%;
    right: 5%;
    width: 20%;
    height: 20%;
    border-radius: 50rem;
    border: 1px solid #fff;
  }
}

.avatar-online {
  @extend %avatar-status;
  &:before {
    background-color: green;
  }
}

.avatar-busy {
  @extend %avatar-status;
  &:before {
    background-color: red;
  }
}

in the CSS the result is:

.avatar-online:before, .avatar-busy:before {
    content: '';
    position: absolute;
    bottom: 5%;
    right: 5%;
    width: 20%;
    height: 20%;
    border-radius: 50rem;
    border: 1px solid #fff;
}

.avatar-online:before {
    background-color: green;
}

.avatar-busy:before {
    background-color: red;
}

You can extend most simple CSS selectors in addition to placeholder classes in Sass, but using placeholders is the easiest way to make sure you aren't extending a class that's nested elsewhere in your styles, which can result in unintended selectors in your CSS.

Note that the CSS in %avatar-status isn't generated, because %avatar-status is never extended.

Conclusion

SASS is wonderful new language. Although it may seem simple, it offers great benefits for developing theming and templates.

If useful, please share it.

Learn SASS and SCSS | Sass & SCSS Tutorial for Beginners

Learn SASS and SCSS | Sass & SCSS Tutorial for Beginners

Learn the program that has helped a million learners worldwide! SASS (Syntactically Awesome Style Sheets) and SCSS (Sassy CSS) that have helped so many people can now be yours at just $9! Dave Moran will explain the elements of these two languages and help you add power to your systems with them.

Description
As a developer, you know the importance of CSS and you also know how CSS can become cumbersome, disorganized and repetitive. Maybe your CSS performs poorly, or, maybe your just spending too much time digging through CSS code to solve minor display issues.

Stop wasting time tearing your hair out over confusing or poor performing CSS.

With Learn SASS and SCSS with Dave Moran, you'll be introduced to to the technologies of SASS (Syntactically Awesome Style Sheets) and SCSS (Sassy CSS). If you're not familiar with these important advances in the CSS world, SASS is a CSS pre-processor with syntax advancements. Style sheets in the advanced syntax are processed, and turned into regular CSS style sheets. SCSS is a super set of CSS, expanded to accommodate the features of SASS. SASS can be used with any version of CSS and all CSS libraries are compatible.

In this course you'll do more than watch demonstrations from an expert instructor. Dave will invite you to code along as you go from SASS newbie to expert. You'll complete this course ready to integrate SASS workflow and SCSS syntax in to your own development projects. To insure that you retain the information presented, Dave has prepared several code exercises to help you get the hang of things.

With over 1,000,000 enrollments world wide LearnToProgram brings you instructors who are teachers first, our instructors are able to take complex technical information and make it understandable for just about anyone. Dave Moran is no exception and you will find his teaching style to be both comfortable and immediately understandable as you learn SASS and SCSS.

Welcome to Learn SASS and SCSS with Dave Moran. See you in class!

Who is the target audience?

Web Developers and Designers
Front End Developers
Software Engineers
Basic knowledge
You should have fundamental knowledge of HTML and CSS
You should be able to use your PC or Mac operating system
What will you learn
Set up a SAAS project
Understand and apply SAAS nesting
Use and apply the concept of Segmentation
Integrate SAAS Variables in to your Work
Understand SCSS Mixins and SCSS Functions
Create your Own Mixins
Know and apply Best Practices
To continue:

What is the difference between CSS and SCSS

What is the difference between CSS and SCSS

The difference between CSS and SCSS is quite subtle. ... readibility

Introduction
  • CSS : Cascading Style Sheet is the basically the scripting language. CSS is used for designing web pages.
    CSS is the most important web technologies that are widely used along with HTML and JavaScript. CSS have file extension of .css.
  • SCSS : Syntactically Awesome Style Sheet is the superset of CSS. SCSS is the more advanced version of CSS. SCSS was designed by Hampton Catlin and was developed by Chris Eppstein and Natalie Weizenbaum. Due to its advanced features it is often termed as Sassy CSS. SCSS have file extension of .scss.

Differences:

1: SCSS contains all the features of CSS and contains more features that are not present in CSS which makes it a good choice for developers to use it.

2: SCSS is full of advanced features.

3: SCSS offers variables, you can shorten your code by using variables. It is a great advantage over conventional CSS.
* Example:
In CSS

body{
 color: #ffffff;
 font: $ubuntu-font: 'Ubuntu', 'Arial', 'Helvetica', sans-serif;
 font-size: xx-large;
 padding: 2rem;
}
**In SCSS**
$white: #ffffff;
$ubuntu-font: $ubuntu-font: 'Ubuntu', 'Arial', 'Helvetica', sans-serif;

body{
 color: $white;
 font: $ubuntu-font;
 font-size: xx-large;
 padding: 2rem;
}

4: Knowing SCSS helps you to customize Bootstrap 4.

5: SASS adds the feature of @import which lets you import your customized SCSS files.
Example:

@import "my theme";
@import "framework/bootstrap";

6:. SASS allows us to use nested syntax. Let’s say if you have to style a specific ‘paragraph’ in ‘div’ in ‘footer’ you can definitely do that by SASS.
Example:

footer {
    div {
        p {
            margin: 2rem;
            color: #2f2f2f;
        }
    }
}

7: At last, what makes SASS a good option to use is that it is well documented.

Thank you for reading !

Top 10 Time-Saving CSS Tips When using Sass

Top 10 Time-Saving CSS Tips When using Sass

These top 10 CSS best practices will help you save time and collaborate better with your team.

These top 10 CSS best practices will help you save time and collaborate better with your team.

We sometimes think that we know all we need to know about SCSS and that we can give that extra time to get ahead on JavaScript.

I’m sorry to be the one breaking this to you, but you should pay more attention to your stylesheets. I’ve worked in projects where the code turned into spaghetti just because a few simple best practices weren’t applied. I quickly learned how precious some good tips can be when working with other people on a code base that can become quite large in no time.

That’s why, today, I’m sharing with you 10 SCSS best practices that will help you and your team.

Start using them, your teammates and the people who’ll later take over your code will thank you. (By the way… that’s one of the few ways you get extra points in the good place.)

Tip 1: Adopt the BEM Convention

Have you ever gotten into a project and didn’t know how to start reading or making sense of the CSS classes naming?

Yeah ♀️we’ve all been there. That’s why whenever I start a new project or join one, one of my first code style optimizations is implementing BEM and making sure that everyone follows it.

BEM stands for Block, Element, Modifiers. The added value that this CSS classes naming convention brings to the table is simple: it allows you to visualize how your template is styled in a structured way.

How it works is even simpler:

  1. You name the main blocks of your page like this for instance: class="button".

  2. Then, name the elements inside each block using two underscores (to show that it’s part of the block): class="button__icon".

  3. And in case you have a variant of that block, use two dashes to name a modifier: class="button button--red".

So in your template, it will look like this:

<button class="button button--blue">
	<img class="button__icon" src="http://www.bem-br.org/img/logo.png" alt="icon-blue"/>
	<p class="button__label">Use BEM</p>
</button>

<button class="button button--red">
	<img class="button__icon" src="http://www.bem-br.org/img/logo.png" alt="icon-red"/>
	<p class="button__label">Please use BEM</p>
</button>

Editing your styles will become much easier, because you’ll be able to visualize the structure of your code:

.button {
	border: none;
	margin: 20px;
	cursor: pointer;

	.button__icon {
		width: 20px;
		height: 20px;
	}

	.button__label {
		color: white;
		padding: 20px 40px;
		text-align: center;
		text-transform: uppercase;
		font-size: 16px;
	}

	// --> MODIFIERS: COLORS <--

	&--blue {
		background-color: blue;
	}

	&--red {
		background-color: red;
	}
}
Tip 2: Don’t Repeat Yourself, Use Variable Extrapolation for Your Block Class Names

If you follow the BEM convention (or are going to), here is another good practice you can follow to speed up your development time: using variable extrapolation. This way, you will not repeat yourself.

It’s pretty simple — you just define your block class in a variable (in the example above it was .button) and replace it using #{$c} in your CSS code.

Let’s use the example above, to see how it works:

$c: “.button” 

#{$c} {
	border: none;
	margin: 20px;
	cursor: pointer;

	&--blue {
		background-color: blue;
	}

	&--red {
		background-color: red;
	}

	#{$c}__icon {
		width: 20px;
		height: 20px;
	}

	#{$c}__label {
		color: white;
		padding: 20px 40px;
		text-align: center;
		text-transform: uppercase;
		font-size: 16px;
	}
}

It’s a small and simple improvement, but not having to rewrite your block class name every time (or just being able to update it in a single spot) speeds things up, improves code readability and makes the structure of your CSS code pop out.

Tip 3: Structure Your Project With InuitCSS

You can think of InuitCSS as a CSS framework. Even though it does not provide you with UI components or anything like that.

Instead, InuitCSS helps you normalize, configure, homogenize and structure your stylesheets.

Sounds abstract? Okay, let’s see how it does that.

First, go ahead and install InuitCSS using npm install inuitcss --save. Now all you have to do is get to know the InuitCSS-specific CSS directory structure that it provides and follow it to set structure you project’s assets:

  • /settings: This is where all your global variables, site-wide settings and configs go. For example, instead of declaring colors variables in every one of my stylesheets, I just put them and organize them in one single file under this folder.

  • /tools: The tools folder is where you define your project mixins and functions, most of the time, I use it to store the Sass mixin I use for responsive media queries.

  • /generic: Here, you can specify low-specificity CSS rules, like normalize.css and reset rulesets.

  • /elements: When you need to style unclassed HTML elements like links, pages, images, tables, and so on, you can simply create a stylesheet in this folder for that.

  • /objects: The objects folder is where you put your objects, abstractions, and design patterns like your layouts.

  • /components: This is where the style of specific UI components goes. Honestly, I never use it, simply because I code my projects with Vue.js and it uses single file components.

  • /utilities: The utilities folder is for all the high-specificity, very explicit selectors like the animations you need to use in your project.

It’s pretty neat, I know!

Tip 4: Use Datasets to Group Your Colors

If you’re using Sass loops, I definitely recommend using datasets, especially if it involves defining colors.

Let’s check this one in play by taking the example of social buttons. As you can probably guess, social buttons (Facebook, Twitter, etc.) have different colors.

So instead of having to write this:

// VARIABLES
$c: ".c-social-button";

#{$c} {
	border: none;
	border-radius: 4px;
	color: $white;
	user-select: none;
	cursor: pointer;

	// --> NETWORKS <--

	&--facebook {
		background: #3b5998;
	}

	&--google {
		background: #db4437;
	}

	&--messenger {
		background: #0084ff;
	}  

	&--twitter {
		background: #1da1f2;
	}
}

You can choose a more elegant way:

// VARIABLES
$c: ".c-social-button";
$networks: facebook, google, messenger, twitter;

// THE DATASET FOR SOCIAL COLORS
$socialColors: (
	facebook: #3b5998,
	google: #db4437,
	messenger: #db4437,
	twitter: #1da1f2
);

#{$c} {
	border: none;
	border-radius: 4px;
	color: $white;
	user-select: none;
	cursor: pointer;

	// --> NETWORKS <--
	@each $network in $networks {
		&--#{network} {
			background: map-get($socialColors, $network);
		}
	}
}
Tip #5: Adopt Veli’s Colorpedia Naming Convention

Okay, you get it and you know it: using terms like light, dark, medium and so on as a naming convention for your project colors is very limiting, simply because there are some projects where you’ll have a lot of color and this is not going to take you very far.

Instead of scratching my head about this one every time, I simply use Veli’s colorpedia. This way you’ll get to give your colors names that a human can understand while not being limited by the light/medium/dark spectrum.

Additional perks come with using Veli’s colorpedia Veli’s colorpedia — it provides you with matching colors and even tells you how a colorblind person sees it.

Some designers are just angels sent from heaven.

Tip 6: Avoid Using Mixins Everywhere

When you don’t have to use mixins, just don’t do it! Why?

Because when you use mixins, they have to be well-structured and maintained in a rigorous way. Using mixins for no good reason is the best way to get lost when the project grows. They can cause side effects and become hard to update when they are used in many places. So use them carefully.

If you don’t know whether and when to use a mixin, remember this one rule: Mixins are here to avoid repeating yourself by keeping a Single Source of Truth.

Also, as of today for example, we don’t have to use mixins to prefix CSS properties because we have plugins like PostCSS Autoprefixer that exist and do the heavy lifting for you.

Tip 7: Supercharge Your Media Queries with SASS MQ

Sass MQ is an open-source mixin crafted by developers working at The Guardian (fancy!). It’s amazing for two reasons:

  • It compiles keywords and px/em values to em-based queries, so when users zoom on your page, the content doesn’t get all scrambled up.

  • It provides fallbacks for older browsers like IE8.

It simply works by compiling this code:

$mq-breakpoints: (
	mobile: 320px,
	tablet: 740px,
	desktop: 980px,
	wide: 1300px
);

@import 'mq';

.foo {
	@include mq($from: mobile, $until: tablet) {
	background: red;
}

@include mq($from: tablet) {
	background: green;
	}
}

Into this:

@media (min-width: 20em) and (max-width: 46.24em) {
	.foo {
		background: red;
	}
}

@media (min-width: 46.25em) {
	.foo {
		background: green;
	}
}

Elegant, simple and useful. What’s not to like?

To start using it, just go ahead and follow the instructions on their GitHub page.

Tip 8: Use CSSComb

One more final thing to get you a clean CSS code. I know that each one of us has our own way of writing CSS code, but doing so will leave you steps behind when working with somebody else or a team on a project.

That’s why I use CSS Comb. I installed the extension on VSCode, and every time I start a new project I set a .csscomb.json file in its root.

This .csscomb.json file includes a configuration that transforms your CSS code and your teammate’s into one single format whenever you run the extension.

You can use my own CSS Comb configuration below, or configure your own just by choosing the way you want your CSS code to look.

Tip 9: Using Placeholders Can Often Be a Great Tool

In a project, I have a set of properties that define a dark background. I very often find myself having to type them over and over again. Here is how using a placeholder can come very handy:

// The placeholder selector
%darkbg {
	border: 1px  solid  #000000;
	background: #101010;
	box-shadow: 0  1px  5px  0  rgba(#404040, 0.6);
}

.my-dark-block-for-errors {
	@extend %darkbg;
	// Some other properties for errors
}

.my-dark-block-for-success {
	@extend %darkbg;
	// Some other properties for success
}

This will compile into the following css code:

.my-dark-block-for-errors, .my-dark-block-for-success {
	border: 1px  solid  #000000;
	background: #101010;
	box-shadow: 0  1px  5px  0  rgba(#404040, 0.6);
}

.my-dark-block-for-errors {
	// Some other properties for errors
}

.my-dark-block-for-success {
	// Some other properties for success
}

Notice how it made our two blocks extend the placeholder? No need to repeat ourselves now and to remember these properties anymore.

Tip 10: Take a Few Minutes to Browse Awesome-Sass.

Awesome-Sass is a curated list of awesome Sass and SCSS frameworks, libraries, style guides and articles. It is a fantastic resource that keeps getting updates as of today. It includes so many interesting resources and it will deepen your Sass skills just by browsing it for a few hours.

For instance, this is where I discovered the Sass Guidelines or Sassline.

I hope this article was useful. Sass will definitely save you time,

Thank you!