Hackernoon logoEpisode 38: Glamouring up your CSS (SASS) by@thatdania

Episode 38: Glamouring up your CSS (SASS)

Dania Mah Hacker Noon profile picture

Dania Mah

Web Developer

It’s been a refreshing Christmas where I’ve arrived back on my two feet after eating lots of food, sitting in hot baths and sleeping throughout. Hope you all have had a lovely Christmas, and today I start with fresh eyes to write about this blogpost together. Before we start,

Why would we want to glamour up our CSS to begin with? Two main reasons:

  • Lots of code to process

If we are working on a grander project, with multiple CSS pages and a website that needs images, it’ll take longer for our website to render.

If we have lots of code written in our CSS, it will become difficult for a developer to read, let alone manage/navigate over time.

SASS is the preprocessor that many developers use to compile their CSS code as minimal as possible. It’s not only more compressed or cleaner, it also fundamentally keeps the foundation and output of its code as CSS. How does this make a difference? Well, SASS allows us to write minimal, elegant, compressed, powerful code and then it will run its “Sass compiler” to convert all of its SASS language into CSS. In other words, computers never know that what we send them is SASS as we use a language converter to communicate with them a language that they are familiar with.

How’s that for a basic explanation on how SASS works? Boom! However, this is where things get a bit crazy! We’re not going to be using Syntactically Awesome Style Sheets! (Dafaq!) No, to glamour things up, we‘re using SCSS (Sassy CSS). From learning it in a day, it seems that the syntax for SCSS and CSS are way more similar, thus way easier to pick up than SASS where there are no semi-colons or brackets.

Many say it’s a design preference. I say, for someone entering the depths of CSS, that it’s the easier swim route to go through. Let’s go through the basics of the SCSS rules and benefits:

How do I get this? (Node and NPM)

What even are these things. Okay.

Node, or Node.js allows one to write and run Javascript applications on the server. It’s a popular language that is used to write tools (SASS) and assist with local web development today. What node is or provides are then packages that a developer could use. However, how would one access, organise or get to these packages?

NPM is a package manager, and a package manager is something every front-end developer uses. It’s almost like a gift-box of tools where one developer could pick what tools they need to write better code with. Without NPM, or a package manager, we will never be able to use or access packages done in Node.

In other words, SASS is a node package and we will be using NPM to access, organise or execute it for us to use. Cool.

Once you have node and npm install, check that you have the versions running by typing in the following command in the terminal:

node -v
npm -v

This will list out the versions you have of node and npm, and show you that you have it. Great, now whatever project you are in, go inside that project folder and run.

npm init 

This will create a package.json file which will hold all the packages (sass) that we will download later. It’ll ask you to fill in details such as name, git repository, description if you want to get into the details. A pretty presentable and structure program npm is.

Now, we simply install the package:

npm install node-sass --save-dev 

So, it’s pretty clear that node-sass is the package. However, what does — save-dev do? It basically updates the package.json file with Sass and puts it as one of the developers dependencies. That way, we don’t have to install it every time and that way, our project knows we need this package always.

Now, enjoy the graphics of it load and install it.

If we want to check that it’s been uploaded and saved in our package.json file, open it up in your editor.

Here, you can see that “node-sass” is saved under the dev Dependencies of the project. Yay, we did it! A note, though:

We only use — save-dev, if the package is a tool for development. For instance, if we wanted to use JQUERY in the project, we wouldn’t use it as it’s file we want to include, not use for developing our project. (Does that make sense, I hope it does). To show the difference in the package.json file, I will install it and show the difference.

See how Jquery is under dependencies instead of devDependencies. It might be a small difference but NPM is used for organising our packages. So if we’re given an organisation feature, we might as well use it to keep our packages listed, clean and know what package is used for what reason.

Now, say if you were working collaboratively as a developer. It’s highly likely. Are you going to commit all of these files below to your github for them to fork?

No! Because that’s what the package.json file is for! The package.json is a file that documents all the packages you download. So if your friend who are sending this code to needs the project, you would just need to send them the files including the package.json. Then, they would just run the following command below considering the fact that they already have npm and node.

npm install 

Boom! It’ll install the thousands of files you saw in the previous image on their computer. What a way to save space on GITHUB or on file transfers, am I right?

However, in this situation, let’s say i don’t need Jquery for this project. Oops, I downloaded a package that I don’t need so why should I keep it. We should never keep packages we don’t use.

npm uninstall jquery --save

And now, if we check our package.json file.

The Jquery has dissapeared! What!

Now we can finally use SASS, but before we do that, let’s look at some concepts SASS or SCSS provides.

Variables:

Here, I’m using CodePen to demonstrate the tool benefits of Sassy CSS. You can see that I’m setting a variable on line 6 with a dollar sign. All I’m setting is the primary colour to a certain colour and then calling the variable on line 10.

The benefit for having variables is that in large scale projects, if we wanted to change a colour, font-size or other elements throughout the project, we could simply change one value and the computer will process that for us! Wicked.

If we want to see how this SASSY CSS is complied into CSS (I explained the concept earlier), it would look like this.

See how our variables are not shown and see how our background colour is set to the variable value we had! Crazy!

Nesting:

This is quite a cool but weird concept for CSS, but it can come really in handy. Let’s say we have a ul with a class called “navigation” and inside it we have multiple <li> and a <p> saying “Here.” Visualise it, great. What do we do when we just want to edit the <li> elements. In CSS, we nest by doing the following:

This is how we do it in CSS, we simply call the class and specify the element. In SCSS, it’s even better and logically makes more sense.

Well you look at that! We can simply call the li element in our navigation class selector! It’s not only cleaner but shorter code with less selectors to look at.

Let’s take another case. Let’s say we have all these <li> elements and we’ve styled it the way we did. However, we can see that the first <li> element is out of place. What do I do to even tackle that. Yep, you guessed it: Nesting. Let’s do it in CSS first.

Great, this should do the trick. However, as we’ve seen earlier that we can nest elements in selectors in SCSS, let’s do it!

Whoa What did I just do there! What is this & symbol? Well, its an ampersand symbol is compiling the selectors we have till it hits that point. In other words, I could write this instead of using the ampersand.

.navigation li:first-child 

This means the same as what the ampersand is saying. Note: The spaces mean a big difference. If we had a sapce between li and :first-child, CSS will take it as two different elements and link between our selectors won’t go through.

What if we wanted to nest things deeper. Let’s say I want to tackle the A object in the li elements, in the ul element with the class “navigation”. There is no limit to nesting (as that’s why they say this is the last level one should nest. In other words, going 3 layers deep is a perfect sponge cake)

And we can nest anything, even pseudo classes which definitely make our CSS cleaner than if we used the original CSS.

A thing about floats:

When we float elements (whether it’s to the right, centre or left), those elements will lose their background colour if one decides to put one. Why is this? This is because the elements we set float too have no height and given they aren’t in a block, the colour we had set can’t be added to the block.

Dilemma. What do we do. ClearFix.

This is a class that we’ll add to the element that affects all elements which is our nav. Then, we write the code for the following class.

To my understanding and from reading it on W3schools, this is a hack for “ If an element is taller than the element containing it, and it is floated, it will overflow outside of its container.” In our case, the float does not have a block or section in place.

What’s important here is the pseudo class we used called “after”, as this is the key to what clears or manages the float method. Inside, we’re setting the content to nothing (as we don’t want our floats to contain anything), clear:both property is the other key that will solve our float problem and display them in a table format. That way, the “rows” I suppose will have a place for the colour to go. [Warning: This is to my understanding, I am be wrong]

This is claimed the safest way to contain a float.

Colour features:

This is something minor but a sweet addition to SCSS. It’s called “HSL features” and SCSS has these things called darken and lighten.

We can use it anywhere, but let’s say I’m using it on the hover for some button. My $color-secondary is a variable, and the method darken will darken the background-colour of the button by 15%. How crazy is that!

Let’s go deeper: Mixins.

In short, mixins are huge variables of reusable code. Why is this useful? Let’s say we wanted to use the clearfix piece of code on multiple selectors in our CSS. If we are following the practice of writing as minimal code as possible or following the DRY principle (Don’t repeat yourself), then it wouldn’t be suggested or wise to copy and paste the clearfix code we wrote earlier into each selector we want to adjust.

If you’re starting to piece the puzzle, yes, we are going to be using mixins to contain the code of the clearfix and call it. I’m telling you it’s a whole nesting situation. Otherwise, think of it like a method (if you’ve coded before)

To make or use a mixin, we call it as such: @mixin . The clearfix is the name of the mixin. To call this mixin we will say @include and the mixins name, which is clearfix.

However, that’s not the only thing!

Mixins can take in arguments. Let’s say our mixin applies to many elements of our code but has one feature that bugs the strategy. Let’s say this is a colour in our mixin, and we need one of our elements to be black to match our design instead of the colour all to be white. We can just do this!

Our mixin now takes in an argument and that argument will be set to the colour property. So, whatever colour we will pass it when this mixin is called, that colour will be inputted in this mixin. For example:

Here, I’m calling that mixin to a selector, and giving it a colour variable which is a variable that holds the colour white. Fabulous.

More Functions:

We’ve already touched on this but you probably didn’t realise or notice it. Things like “darken” and “lighten” are functions, where they take in arguments depending on how they are built.

If one has coded, one knows what functions or methods are (basically code that executes actions with the code in a jist). Although SASS or SCSS has inbuilt functions, we can also write our own functions!

Although this sounds like a great opportunity to use, one questions why would you need to write your own functions given that even if we were writing math operations, SCSS and SASS allow us to just put a “+” into the code…(Hmm, more for discovery later).

However, let’s do a function to show how a function could work.

Here, I’m doing a simple divide function where I take two arguments (or in this case, numbers), and return it. (Ignore the addition sign as I can’t be bothered to remove it).

Now, if we call it.

Here, on the margin property in the nav selector, we equip this method. If we want the margin to be 30 px, we put (60,2) as the numbers! However, why have I put a * 1px afterwards. See, if we don’t, SCSS wouldn’t know what unit we would want that number to be. It could be percentages, it could be pixels or em! Hence, a safe way to make sure our unit is a pixel (or the unit we choose), we should multiply our pixels by 1.

I’m assuming you can do this in the method we set as well. However, this is a great example to show you how we can use functions and math operations in SCSS.

Extends:

So far, mixins and functions are ways where we can refactor our CSS code and tools that give us more control over what we can input into our CSS code. Extends is another tool we can use, to do the same and as the name suggest, we are “extending code” into elements.

This may come useful when we have multiple buttons on our page with the same style and effects. Let’s say we have two buttons that do exactly the same thing. How can we refactor this?

We’ve got too many btn-mains, btn-hots repeating here. Let’s refactor using an extend as such.

So, what I’ve done here is that I’ve put the button styling code into a placeholder (calling it with %) and extending that placeholder in the .btn-main selector. Although you may think that now the placeholder is being applied to the btn-main selector, you are mistaken.

[An important note, notes]:

If we take mixins and extends, they work the same way but what’s different about them is “what code is applying to what.”

  • With mixins, when we make a mixin and call it, that mixin is being applied to whatever selector we call it on.
  • With extends, when we make an extend and call it, the selector we call it on is being applied to the extend.

Hence, in our extend example our btn-main selector is being applied to the btn-placeholder. Freaky concept but try soak that in.

If you’re having a hard time figuring it out in your head, I would like to think mixins and extends are opposites of each other…in terms of what code is being applied to what.

What would be interesting if you ever code in SASS on codePen, you can see your compiled SCSS, which shows you how the computer will end up reading it. It’ll show you what code is not shown (variables) and what code each selector has decided to consider.

In the compiled CSS after SCSS has preprocessed.

A rule for extends is that you should you use them if the rules for the elements are related inherently or thematically to each other.

What does that mean. Well, the buttons are thematically related given that they are buttons on a website. Speaking from a design perspective, there’s a likely chance we want our buttons to look the same or have most of the same characteristics. Inherently would mean if they inherit from one another, which is still a foggy mystery I have yet to explore (Hence, I won’t go into it)

In the image above, you can see that the compiled CSS has placed both these elements/selectors with the following properties. This can be seen as a future maintenance issue down the line, if the selectors styled don’t relate inherently or thematically. For instance, what if we wanted to change one property in this situation where these buttons are not related? It’ll take more time for us to go back and have a high chance of re-editing the code immensely.

Writing and Compiling our SCSS/SASS files.

Like every type of file, it has a place where it belongs amongst our files of code. Hence, we are going to make a SASS folder in our project folder.

mkdir sass

Change into the project directory, and make a scss file. Given we’ve been talking about scss all this time. (Main is the name of the sassy css file)

cd sass
touch main.scss

Now, once you have written your sassy css code into this file you’ve made. We’re now going to go into your package.json file, where we are going to adjust the scripts in order to compile these files.

You will see that in your scripts, you already have something written there. This is a predefined script that you can change, and we will change.

Now, what we are writing in the scripts is the script we’re going to call to compile our css. We need to mention the package and the files that our script should compile as such.

So, here we are calling the script compile:sass and then calling on the package we downloaded along with the file we want to compile. However, when we compile the code, this compiled code needs to go somewhere and so, we will make sure it goes into a css file with the same name, in the css folder, because we want to be clean and neat developers/

So, in order to finally compile your sassy css files to css, we would need to run the following code in our command line/terminal below:

npm run compile:sass

And now, if you check your css/main.css or whatever name your css file is, it should have compiled all your sassy css code into that file!

However, here is where we come into dilemas.

*Raises hand, yes sir!

“What if I edit my Sassy CSS file, and want to see the changes in my CSS file. Does this mean I have to run that npm line every time I do it?”

Great question, and we’re going to add something small so that our script knows to watch out for the changes.

Will you check that out, all it takes is a -w and that will notify our code to watch out for any changes that happens between our sass or css files! You can check in the terminal for the changes when you run the “npm run compile:sass” as it print out the changes you do on your code in your text editor simultaneously! Technology man!

Note: I believe you can do this with sass commands as well.

sass — watch main.scss:main.css
“What if I want to compile multiple files in the script!

Very good question, using the Sass command, you can do this.

sass — watch main.scss:main.css

However, if we are changing our scripts, we can write the code as such.

"compile:sass": "node-sass scss -o css -w"

This piece of code from what I’ve read in the article below, should compile all your sass code in css files. I’m under the assumption you would have to make these CSS files empty first so that your compiled code can go somewhere, but give it a try to see what works for you.

I’ve read that it doesn’t matter where you put the “-w” or “watch, as long as it’s before the scss and after the node-sass…

For more information the link is below:

“What if I want to see my changes automatically happen on screen?

Amazing question and a useful one to keep in mind. Here, we are going to need a live-server to see all our changes on screen every time we make a change. This is so we don’t have to go refresh the page every time, or write up code every time.

We’re going to want to install this package globally because we want to use it anywhere on our project, in any project and anywhere on our computer. As we all know, this will definitely come in handy more than just one project.

npm install live-server -g 

You won’t be able to find it in your project folders as we installed in globally. Thus, the only way to check it is if run live-sever on our terminal. Note: Run live-server in the folder in another window as you might want to keep your other terminal windows for other users (checking your process on sass or running other pieces of code, etc.)

live-server

This should open your project in your default browser. You should now see two things now.

  • See that your project is opened on the default browser
  • That it’s connected to some local host, (a bunch of numbers such as 127.0.01:1800)

You guessed it, the only way to test whether it works is to change something in your CSS, SCSS file and see whether your default browser page changes anything.

On that note, comment below for any feedback or additional ideas and your welcome for the 17 minutes of SCSS, SASS summarised.

~See you next time

Fun fact of the Day/ Update of the Day:

I start the last three weeks of my coding bootcamp nextweek. It’s pretty daunting, with a lot of “it’s time to get serious stuff”. Interviews and final projects. Exciting, yes. Prepared, one is never prepared.

So, don’t expect everyday blogs to come back for these three weeks. However, it doesn’t hurt to check as I might be documenting my final project or god knows what I’m writing about then.

If not, check out the things I’ve been up to, check out my github on my insta.

Both are under @thatdania

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.