惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
B
Blog RSS Feed
W
WeLiveSecurity
I
InfoQ
L
Lohrmann on Cybersecurity
Simon Willison's Weblog
Simon Willison's Weblog
腾讯CDC
S
Schneier on Security
酷 壳 – CoolShell
酷 壳 – CoolShell
T
Threat Research - Cisco Blogs
P
Palo Alto Networks Blog
Attack and Defense Labs
Attack and Defense Labs
I
Intezer
Recent Commits to openclaw:main
Recent Commits to openclaw:main
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Last Week in AI
Last Week in AI
WordPress大学
WordPress大学
Cisco Talos Blog
Cisco Talos Blog
T
The Exploit Database - CXSecurity.com
S
Securelist
T
Tailwind CSS Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
美团技术团队
Stack Overflow Blog
Stack Overflow Blog
T
Tor Project blog
博客园 - 叶小钗
Engineering at Meta
Engineering at Meta
Microsoft Security Blog
Microsoft Security Blog
Project Zero
Project Zero
C
Cybersecurity and Infrastructure Security Agency CISA
Apple Machine Learning Research
Apple Machine Learning Research
V
Visual Studio Blog
Know Your Adversary
Know Your Adversary
T
The Blog of Author Tim Ferriss
N
News and Events Feed by Topic
小众软件
小众软件
G
Google Developers Blog
F
Full Disclosure
O
OpenAI News
The Last Watchdog
The Last Watchdog
G
GRAHAM CLULEY
TaoSecurity Blog
TaoSecurity Blog
U
Unit 42
Jina AI
Jina AI
S
SegmentFault 最新的问题
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
P
Proofpoint News Feed
Y
Y Combinator Blog
N
News and Events Feed by Topic
K
Kaspersky official blog

Bryan Robinson's Blog

Does our technology still work for us? Product pricing, dev bad habits, and the role of the pit of success Astro Server Island for latest Bluesky post (heavily cached!) Type-safe environment variables in Astro 5.0 New Website, but really is it? Netlify Durable Cache: Caching for a third-party world Introducing the Hygraph Astro Content Loader Integrating Astro.js Starlight Documentation into a Next.js Project Using Proxies Jamstack is meaningless 😱 Book Release: Eleventy by Example – Learn 11ty with 5 in-depth projects 11ty Second 11ty: Creating Template Filters 11ty Second 11ty: Global Data files (JS and JSON) 11ty second 11ty: The Render Plugin Part 1 Help needed: Netlify Frontend environment variables with Astro.js Quick experiment with the Slinkity 11ty plugin Creating a dynamic color converter with 11ty Serverless Using 11ty JavaScript Data files to mix Markdown and CMS content into one collection How to show your template code in 11ty blog posts New City, New Job, New Content Using Nunjucks Climbing the 11ty Performance leaderboard with Cloudinary, critical CSS and more Three JAMstack movements to watch in 2020 Create a Codepen promo watermark with no additional HTML, CSS or JS 3 underused CSS features to learn for 2020 Use CSS Subgrid to layout full-width content stripes in an article template Adapt client-side JavaScript for use in 11ty (Eleventy) data files CSS Gap creates a bright future for margins in Flex as well as Grid Create your first CSS Custom Properties (Variables) Use CSS Grid to create a self-centering full-width element Creating an 11ty Plugin - SVG Embed Tool Now offering design and code reviews at PeerReviews.dev Routing contact-form emails to different addresses with Netlify, Zapier and SendGrid Create an Eleventy (11ty) theme based on a free HTML template Client work and the JAMstack Grid vs. Flex: A Tale of a "Simple" Promo Space Using Eleventy The Tech Barrier to Entry What Can We Learn from CERN Let Practical CSS Grid - Launching My First Course Build Trust on the Web incorporating User Worries with your User Stories 2019 The Year of Markup-First Development Starting a new journey with Code Contemporary Dynamic Static Sites with Netlify and iOS Shortcuts Top 3 uses for the ::before and ::after CSS pseudo elements How To: Use CSS Grid to Mix and Match Design Patterns Use CSS ::before and ::after for simple, spicy image overlays Modern CSS: Four Things Every Developer and Designer Should Know About CSS 3 Strategies for Getting Started with CSS Grid CSS Tip: Use rotate() and skew() together to introduce some clean punk rock to your CSS The 5 Stages of Grid Love How To: A CSS-Only Mobile Off Canvas Navigation How To: Use CSS Grid Layout to Make a Simple, Fluid Card Grid Make a More Flexible Cover Screen with CSS Grid Can CSS Grid open up interesting CMS Layout options? Firefox 52 to Introduce New Box-Alignment Values Falling Forward — Rethinking Progressive Enhancement, Graceful Degradation and Developer Morality Start Exploring the Magic of CSS Grid Layout I Converted My Blog to CSS Grid Layout and Regret Nothing Feature Queries are on the Rise CSS Shapes — Let the Text Flow Around You Flexbox -- Let Memorializing Prince and Print vs. The Web I went to Italy and noticed UX fails How to Get Designers to Contribute in Open Source The True Gift of Your Former Code
Refactoring CSS into a Sass mixin
2018-11-28 · via Bryan Robinson's Blog

Graphic refactoring CSS to Sass

I’ve begun live-streaming office hours every week. In my first effort at it, I mostly just worked on this site’s code. I decided to create a new promo style for articles and realized I needed to refactor some of my Sass. 

It struck me as I was writing a new Sass mixin that there may be designers and developers out there that haven’t translated vanilla CSS into a Sass function. In this article, I want to show how to take often-used CSS and convert it into a DRY (Don’t Repeat Yourself) Sass mixin.

The Starting CSS

Usually when I talk about Sass mixins, I like to show the power on buttons. That’s not always the most applicable use case, though. In this instance, we’ll take the “interesting border” concept from my “Top 3 uses of ::before and ::after” and convert it to a reusable Sass component.

In this case, we need to affect four main elements with our CSS. The parent element, a universal (*) set of elements inside the parent and a ::before and ::after pseudo-element.

.article-promo {
    position: relative;
    padding: 20px;
}
.article-promo > * {
    z-index: 100;
    position: relative;
}
.article-promo::before {
    background-color: white;
    content: "";
    display: block;
    position: absolute;
    top: 10px;
    left: 10px;
    width: calc(100% - 20px);
    height: calc(100% - 20px);
    z-index: 0;
}
.article-promo::after {
    background-image: linear-gradient(120deg, #eaee44, #33d0ff);
    content: "";
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 0;
    mix-blend-mode: screen;
}

Taking a look at this code, you can see that it would be a lot to create by hand every time we wanted to do a different gradient border.

{% include ad-space.html %}

Step 1: Identify potential Sass variables

One of the best reasons to start using Sass is its variables. In this case, we’re going to use variables to create customizable properties for our border.

I’ll start by finding things I want to change on a per-implementation.

For a gradient border, I’ll want to adjust the “border size,” the start color, the end color, original background color and the direction of the gradient.

Let’s move those values out into variables at the top of our CSS.

$border-size: 10px;
$original-background-color: white;  
$gradient-start-color: #eaee44;  
$gradient-end-color: #33d0ff;  
$gradient-direction: 120deg;

Where we were originally using static values, we’ll now replace those with the variables.


.article-promo::before {
    ...
    background-color: $original-background-color;
    top: $gradient-size;
    left: $gradient-size;
    width: calc(100% - #{$gradient-border-size * 2});
    height: calc(100% - #{$gradient-border-size * 2});
    ...
}

.article-promo::after {
     background-image: linear-gradient($gradient-direction, $gradient-start-color, $gradient-end-color);
}

Note the #{} syntax in our calc() function in this example. This is a use case of a concept called variable interpolation. Most languages have some form of this.

In the case of Sass, we use that syntax mostly when inside of a CSS function. In this case, Sass sees the calc() function and intends to compile the entire thing as one string to your CSS. The #{} syntax causes Sass to pause its compile and render the value into that string instead.

Step 2: Identify and refactor repeated code with @extends

In our example, we have two absolutely positioned pseudo-elements. These come with four properties that are identical: content, display, position and z-index.

We’ll use Sass’s @extend method to refactor this into a concise bit of compiled CSS.

Side Note: Why use @extend instead of creating a mixin and using @include here? @extend will create one rule set in CSS for multiple selectors; @include will insert the same rule set into the compiled CSS. Extending in Sass is a great way to reduce complexity and size of compiled CSS. Here are the docs on extending.

We’ll start by creating a “dummy” selector for our properties.


%pseudo-properties {
    content: "";  
    display: block;  
    position: absolute;
    z-index: 0;
}

Note that % in there. That’s not standard CSS. We use that so that we don’t generate the CSS until it’s called. This keeps selector bloat down a little bit.

We can then reference that fake selector with the @extend method on our pseudo elements.

.article-promo::before {  
   @extend %pseudo-properties;
    ...
}

.article-promo::after {  
   @extend %pseudo-properties;
    ...
}

The compiled CSS will look like this: 

.article-promo::before, .article-promo::after {
    content: "";
    display: block;
    position: absolute;
    z-index: 0;
}

The other code in your definition block for ::before or `::after will be compiled into its own selector later. You can keep your code together this way and not worry about bloat.

Step 3: Nest your selectors for easier abstraction

We can use Sass’s nesting abilities to clean up our code a little. 

This will also help as we extend the functionality to any other selector than our current one.

.article-promo {
    position: relative;
    padding: $border-size * 2;
    > * {
        z-index: 100;
        position: relative;
    }
    &::before {
        @extend %pseudo-properties;
        background-color: $original-background-color;
        top: $gradient-size;
        left: $gradient-size;
        width: calc(100% - #{$gradient-border-size * 2});
        height: calc(100% - #{$gradient-border-size * 2});
    }
    &::after {
        @extend %pseudo-properties;
        background-image: linear-gradient($gradient-direction, $gradient-start-color, $gradient-end-color);
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        mix-blend-mode: screen;
    }

Step 4: Move border functionality into a mixin

Here’s the big move. We’ll take everything that we’ve written inside our main selector and move it into an @mixin declaration.

We don’t need the main selector because that’s where we’ll apply our mixin. We don’t need the variables, because they will be arguments in our mixin.


@mixin gradient-border() {
    position: relative;
    padding: $border-size * 2;
    > * {
        z-index: 100;
        position: relative;
    }
    &::before {
        @extend %pseudo-properties;
        background-color: $original-background-color;
        top: $gradient-size;
        left: $gradient-size;
        width: calc(100% - #{$gradient-border-size * 2});
        height: calc(100% - #{$gradient-border-size * 2});
    }
    &::after {
        @extend %pseudo-properties;
        background-image: linear-gradient($gradient-direction, $gradient-start-color, $gradient-end-color);
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        mix-blend-mode: screen;
    }
}

Just like in a function definition in JavaScript, we’ll pass our variables into the parentheses.

You can even specify default values. In my case, I’m keeping a consistent border with small tweaks, so I opted for default values.

@mixin gradient-border($border-size: 10px, $original-background-color: white, $gradient-start-color: #eaee44, $gradient-end-color: #33d0ff, $gradient-direction: 120deg) {
    ...
}

Step 5: Declare the mixin in the selectors you need it

Finally, we have a mixin that we can use. We’ll use the Sass @include method. Here are a few examples.

.article-promo {  
   @include gradient-border; // Gives all defaults
}
.big-border {
    @include gradient-border(50px); // If declared in order, you don't have to label your arguments
}
.red-gradient {
    @include gradient-border($gradient-start-color: red, $gradient-end-color: darkred);
}

.vertical-gradient {
    @include gradient-border($gradient-direction: to bottom);
}

Using this for other examples

This direction will work for any CSS you want to refactor. Sass gives us a lot of power and flexibility. It can either be something that becomes easy to maintain or a nightmare of redeclared variables and nesting. 

Creating reusable components is at the heart of any maintanence strategy. Follow this path and you can create components throughout any project.

  1. Identify reusable components
  2. Find pieces that need to be changed regularly
  3. Nest selectors for simplicity
  4. Use @extend to keep your compiled CSS smaller

What component will you start with?