3 Things you might not know SASS can do

Making your code clever and maintainable

Week 135 was posted by Charanjit Chana on 2020-05-25.

I love working with CSS, it's such a powerful tool when used right. Over 10 years ago, I came across LESS and was converted very quickly. SASS has been around longer, but it wasn't really on my radar and LESS was just fine.

Then around 5 years ago, I was introduced to CodeKit and SASS via Bourbon and it's been my preprocessor of choice ever since.

In reality, I've used SASS to keep my CSS readable and maintainable, but there are some really nice features that you may not be aware of.

1. Apply rgba calculations to HEX codes

You can take your HEX code and pass it to a rgba function to apply alpha to it. Modern browsers already allow you to add an additional two digits to your HEX colour code to determine it's opacity, but that's not supported everywhere.

color: rgba(#F00, 0.5); // rgba(255, 0, 0, 0.5)

Instead of specifying the reg, green, and blue values, pass the colour code and it will get converted. This is really useful for when you have variables to specify your colours already set up. No need to store or calculate the rgb values, just pass the variable and away you go!

color: rgba($myColor, 0.5);

2. Nest media queries

A relatively new one for me and one that I wasn't sold on initially. If you have a lot of things that depend on screen size, this makes it much more maintainable and obvious when things will change.

.myClass { width: 100%; @media screen and (min-width: 800px) { max-width: 800px; } }

A simple example, but when you're looking at the definition for .myClass you'll now know exactly what responsive attributes it has.

3. Apply maths to colours

Colour palettes can be hard but what you can do is add and subtract colours from each other. This allows you to create new shades of colours to to blend them together.

element { color: ($myColour1 + $myColour2); }

I've wrapped them in brackets to remove any doubt as to what should happen but it's not required. You can pass variables or colour codes.

element { color: (#111 + #333); //color: #444 }

Example on CodePen

I put together a really simple example to show what's possible, feel free to check it out.

Update

Turns out that #3 is dependent on your SASS compiler. The libsass compiler has no issues, but Dartsass doesn't.


Tags: css, development, sass, css, development, sass


Tweet WhatsApp Keep Upvote Digg Tumblr Pin Blogger LinkedIn Skype LiveJournal Like