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

推荐订阅源

大猫的无限游戏
大猫的无限游戏
K
Kaspersky official blog
Apple Machine Learning Research
Apple Machine Learning Research
B
Blog
aimingoo的专栏
aimingoo的专栏
M
MIT News - Artificial intelligence
小众软件
小众软件
云风的 BLOG
云风的 BLOG
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Hugging Face - Blog
Hugging Face - Blog
S
SegmentFault 最新的问题
Stack Overflow Blog
Stack Overflow Blog
量子位
S
Secure Thoughts
G
GRAHAM CLULEY
C
CXSECURITY Database RSS Feed - CXSecurity.com
人人都是产品经理
人人都是产品经理
雷峰网
雷峰网
T
Threat Research - Cisco Blogs
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Cisco Talos Blog
Cisco Talos Blog
G
Google Developers Blog
爱范儿
爱范儿
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
有赞技术团队
有赞技术团队
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Martin Fowler
Martin Fowler
The GitHub Blog
The GitHub Blog
Google DeepMind News
Google DeepMind News
C
Cisco Blogs
D
Darknet – Hacking Tools, Hacker News & Cyber Security
博客园 - 聂微东
宝玉的分享
宝玉的分享
H
Hackread – Cybersecurity News, Data Breaches, AI and More
N
Netflix TechBlog - Medium
Forbes - Security
Forbes - Security
Engineering at Meta
Engineering at Meta
S
Security Affairs
Help Net Security
Help Net Security
博客园 - 三生石上(FineUI控件)
AWS News Blog
AWS News Blog
博客园 - 叶小钗
Recent Commits to openclaw:main
Recent Commits to openclaw:main
V2EX - 技术
V2EX - 技术
Hacker News: Ask HN
Hacker News: Ask HN
Project Zero
Project Zero
H
Heimdal Security Blog
W
WeLiveSecurity
C
Check Point 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?