Table of Contents
Other use cases
Dig deeper
Home Web Front-end CSS Tutorial Efficient Infinite Utility Helpers Using Inline CSS Custom Properties and calc()

Efficient Infinite Utility Helpers Using Inline CSS Custom Properties and calc()

Mar 21, 2025 am 10:45 AM

Efficient Infinite Utility Helpers Using Inline CSS Custom Properties and calc()

Recently I wrote a very basic Sass loop that outputs multiple padding and margin utility classes. Nothing special, just a Sass map with 11 spacing values, loops are used to create the class of padding and margins on each side. As we will see, this works, but will eventually produce a fair amount of CSS. We will refactor it to customize properties using CSS and make the system more concise.

Here is the original Sass implementation:

 <code>$space-stops: ( '0': 0, '1': 0.25rem, '2': 0.5rem, '3': 0.75rem, '4': 1rem, '5': 1.25rem, '6': 1.5rem, '7': 1.75rem, '8': 2rem, '9': 2.25rem, '10': 2.5rem, ); @each $key, $val in $space-stops { .p-#{$key} { padding: #{$val} !important; } .pt-#{$key} { padding-top: #{$val} !important; } .pr-#{$key} { padding-right: #{$val} !important; } .pb-#{$key} { padding-bottom: #{$val} !important; } .pl-#{$key} { padding-left: #{$val} !important; } .px-#{$key} { padding-right: #{$val} !important; padding-left: #{$val} !important; } .py-#{$key} { padding-top: #{$val} !important; padding-bottom: #{$val} !important; } .m-#{$key} { margin: #{$val} !important; } .mt-#{$key} { margin-top: #{$val} !important; } .mr-#{$key} { margin-right: #{$val} !important; } .mb-#{$key} { margin-bottom: #{$val} !important; } .ml-#{$key} { margin-left: #{$val} !important; } .mx-#{$key} { margin-right: #{$val} !important; margin-left: #{$val} !important; } .my-#{$key} { margin-top: #{$val} !important; margin-bottom: #{$val} !important; } }</code>
Copy after login

This code works well and outputs all the required utility classes. However, it can also quickly become bloated. In my case, they are about 8.6kb when uncompressed and less than 1kb after compression. (Brotli is 542 bytes, gzip is 925 bytes.)

Since they are very repetitive, the compression works great, but I still can't get rid of the feeling that all of these classes are redundant. Also, I didn't even make any small/medium/large breakpoints that are fairly typical for this type of helper class.

Here is a artificial example of a responsive version after adding a small/medium/large class. We will reuse the $space-stops map defined earlier and put the duplicate code into the mixin

 <code>@mixin finite-spacing-utils($bp: '') { @each $key, $val in $space-stops { .p-#{$key}#{$bp} { padding: #{$val} !important; } .pt-#{$key}#{$bp} { padding-top: #{$val} !important; } .pr-#{$key}#{$bp} { padding-right: #{$val} !important; } .pb-#{$key}#{$bp} { padding-bottom: #{$val} !important; } .pl-#{$key}#{$bp} { padding-left: #{$val} !important; } .px-#{$key}#{$bp} { padding-right: #{$val} !important; padding-left: #{$val} !important; } .py-#{$key}#{$bp} { padding-top: #{$val} !important; padding-bottom: #{$val} !important; } .m-#{$key}#{$bp} { margin: #{$val} !important; } .mt-#{$key}#{$bp} { margin-top: #{$val} !important; } .mr-#{$key}#{$bp} { margin-right: #{$val} !important; } .mb-#{$key}#{$bp} { margin-bottom: #{$val} !important; } .ml-#{$key}#{$bp} { margin-left: #{$val} !important; } .mx-#{$key}#{$bp} { margin-right: #{$val} !important; margin-left: #{$val} !important; } .my-#{$key}#{$bp} { margin-top: #{$val} !important; margin-bottom: #{$val} !important; } } } @include finite-spacing-utils; @media (min-width: 544px) { @include finite-spacing-utils($bp: '_sm'); } @media (min-width: 768px) { @include finite-spacing-utils($bp: '_md'); } @media (min-width: 1024px) { @include finite-spacing-utils($bp: '_lg'); }</code>
Copy after login

It is about 41.7kb when uncompressed (Brotli is about 1kb and gzip is about 3kb). It still compresses well, but it's a little ridiculous.

I know that data-* attribute can be referenced from CSS using the [attr() function, so I'm wondering if it's possible to use calc() and attr() together, create a dynamically computed spacing utility helper through data-* attributes (e.g. data-m="1" or data-m="1@md" ) and then do something like margin: calc(attr(data-m) * 0.25rem) in CSS (assuming I'm using spacing scales in increments of 0.25rem). This can be very powerful.

But the end of the story is: you can't (currently) use attr() with any attribute except content attribute. Too bad. But while searching for attr() and calc() information, I found this interesting comment by Simon Rigét on Stack Overflow, which suggests setting CSS variables directly in inline style properties. Ahha!

Therefore, the following can be performed:<div style="--p: 4;"> , and then in CSS:<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"> &lt;code&gt;:root { --p: 0; } [style*='--p:'] { padding: calc(0.25rem * var(--p)) !important; }&lt;/code&gt;</pre><div class="contentsignin">Copy after login</div></div> <p> In <code>style="--p: 4;" example, you will effectively get padding: 1rem !important; .

…Now you have an infinitely scalable spacing utility class Monster Assistant.

Here is what it might look like in CSS:

 <code>:root { --p: 0; --pt: 0; --pr: 0; --pb: 0; --pl: 0; --px: 0; --py: 0; --m: 0; --mt: 0; --mr: 0; --mb: 0; --ml: 0; --mx: 0; --my: 0; } [style*='--p:'] { padding: calc(0.25rem * var(--p)) !important; } [style*='--pt:'] { padding-top: calc(0.25rem * var(--pt)) !important; } [style*='--pr:'] { padding-right: calc(0.25rem * var(--pr)) !important; } [style*='--pb:'] { padding-bottom: calc(0.25rem * var(--pb)) !important; } [style*='--pl:'] { padding-left: calc(0.25rem * var(--pl)) !important; } [style*='--px:'] { padding-right: calc(0.25rem * var(--px)) !important; padding-left: calc(0.25rem * var(--px)) !important; } [style*='--py:'] { padding-top: calc(0.25rem * var(--py)) !important; padding-bottom: calc(0.25rem * var(--py)) !important; } [style*='--m:'] { margin: calc(0.25rem * var(--m)) !important; } [style*='--mt:'] { margin-top: calc(0.25rem * var(--mt)) !important; } [style*='--mr:'] { margin-right: calc(0.25rem * var(--mr)) !important; } [style*='--mb:'] { margin-bottom: calc(0.25rem * var(--mb)) !important; } [style*='--ml:'] { margin-left: calc(0.25rem * var(--ml)) !important; } [style*='--mx:'] { margin-right: calc(0.25rem * var(--mx)) !important; margin-left: calc(0.25rem * var(--mx)) !important; } [style*='--my:'] { margin-top: calc(0.25rem * var(--my)) !important; margin-bottom: calc(0.25rem * var(--my)) !important; }</code>
Copy after login

This is very similar to the first Sass loop above, but there are no 11 loops - but it is infinite. It's about 1.4kb uncompressed, Brotli is 226 bytes and gzip is 284 bytes.

If you want to extend this to a breakpoint, the unfortunate message is that you can't put the "@" character in the CSS variable name (although strangely it's allowed to use emojis and other UTF-8 characters). So you might be able to set variable names like p_sm or sm_p. You have to add some extra CSS variables and some media queries to handle all of this, but it won't grow exponentially like the traditional CSS class name created using a Sass for loop.

The following is the equivalent responsive version. We will use Sass mixin again to reduce duplication:

 <code>:root { --p: 0; --pt: 0; --pr: 0; --pb: 0; --pl: 0; --px: 0; --py: 0; --m: 0; --mt: 0; --mr: 0; --mb: 0; --ml: 0; --mx: 0; --my: 0; } @mixin infinite-spacing-utils($bp: '') { [style*='--p#{$bp}:'] { padding: calc(0.25rem * var(--p#{$bp})) !important; } [style*='--pt#{$bp}:'] { padding-top: calc(0.25rem * var(--pt#{$bp})) !important; } [style*='--pr#{$bp}:'] { padding-right: calc(0.25rem * var(--pr#{$bp})) !important; } [style*='--pb#{$bp}:'] { padding-bottom: calc(0.25rem * var(--pb#{$bp})) !important; } [style*='--pl#{$bp}:'] { padding-left: calc(0.25rem * var(--pl#{$bp})) !important; } [style*='--px#{$bp}:'] { padding-right: calc(0.25rem * var(--px#{$bp})) !important; padding-left: calc(0.25rem * var(--px)#{$bp}) !important; } [style*='--py#{$bp}:'] { padding-top: calc(0.25rem * var(--py#{$bp})) !important; padding-bottom: calc(0.25rem * var(--py#{$bp})) !important; } [style*='--m#{$bp}:'] { margin: calc(0.25rem * var(--m#{$bp})) !important; } [style*='--mt#{$bp}:'] { margin-top: calc(0.25rem * var(--mt#{$bp})) !important; } [style*='--mr#{$bp}:'] { margin-right: calc(0.25rem * var(--mr#{$bp})) !important; } [style*='--mb#{$bp}:'] { margin-bottom: calc(0.25rem * var(--mb#{$bp})) !important; } [style*='--ml#{$bp}:'] { margin-left: calc(0.25rem * var(--ml#{$bp})) !important; } [style*='--mx#{$bp}:'] { margin-right: calc(0.25rem * var(--mx#{$bp})) !important; margin-left: calc(0.25rem * var(--mx#{$bp})) !important; } [style*='--my#{$bp}:'] { margin-top: calc(0.25rem * var(--my#{$bp})) !important; margin-bottom: calc(0.25rem * var(--my#{$bp})) !important; } } @include infinite-spacing-utils; @media (min-width: 544px) { @include infinite-spacing-utils($bp: '_sm'); } @media (min-width: 768px) { @include infinite-spacing-utils($bp: '_md'); } @media (min-width: 1024px) { @include infinite-spacing-utils($bp: '_lg'); }</code>
Copy after login

About 6.1kb is uncompressed, Brotli is 428 bytes and gzip is 563 bytes.

I think writing like<div style="--px:2; --my:4;"> Is this HTML pleasing to the eye, or good developer ergonomics... no, not special. But is this approach feasible in some cases, such as if you (for some reason) need very little CSS, or do not need external CSS files at all? Yes, of course I think it can. It is worth pointing out here that CSS variables assigned in inline styles do not leak. They act only on the current element and do not change the value of the global variable. Thank God! One weird thing I've found so far is that DevTools (at least in Chrome, Firefox, and Safari) won't report styles using this technique in the Compute Styles tab.<p> It is also worth mentioning that I have used the traditional padding and margin properties as well as -top, -right, -bottom and -left, but you can use equivalent logical properties such as padding-block and padding-inline. By selectively mixing and matching logical and traditional properties, it is even possible to reduce a few bytes. In this way, I managed to compress Brotli to 400 bytes and gzip to 521 bytes.</p> <h3 id="Other-use-cases"> Other use cases</h3> <p> This seems to be best suited for things with linear incremental proportions (that's why padding and margin seem to be a good use case), but I can see that this might work for width and height (number of columns and/or width) in a grid system. <strong>Maybe</strong> it works for typography (but maybe not).</p> <p> I'm very concerned about file size, but there may be some other uses here that I didn't think of. Maybe <strong>you</strong> won't write your code this way, but the critical CSS tool might refactor the code to use this method.</p> <h3 id="Dig-deeper"> Dig deeper</h3> <p> When I digged into it, I found that Ahmad Shadeed discussed mixing <code>calc() with CSS variable assignments in inline styles, especially for avatar sizes. Miriam Suzanne's article on Smashing Magazine in 2019 doesn't use calc() but shares some amazing features that can be achieved using variable assignments in inline styles.

The above is the detailed content of Efficient Infinite Utility Helpers Using Inline CSS Custom Properties and calc(). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
A Comparison of Static Form Providers A Comparison of Static Form Providers Apr 16, 2025 am 11:20 AM

Let’s attempt to coin a term here: "Static Form Provider." You bring your HTML

A Proof of Concept for Making Sass Faster A Proof of Concept for Making Sass Faster Apr 16, 2025 am 10:38 AM

At the start of a new project, Sass compilation happens in the blink of an eye. This feels great, especially when it’s paired with Browsersync, which reloads

Weekly Platform News: HTML Loading Attribute, the Main ARIA Specifications, and Moving from iFrame to Shadow DOM Weekly Platform News: HTML Loading Attribute, the Main ARIA Specifications, and Moving from iFrame to Shadow DOM Apr 17, 2025 am 10:55 AM

In this week&#039;s roundup of platform news, Chrome introduces a new attribute for loading, accessibility specifications for web developers, and the BBC moves

The Deal with the Section Element The Deal with the Section Element Apr 12, 2025 am 11:39 AM

Two articles published the exact same day:

How We Tagged Google Fonts and Created goofonts.com How We Tagged Google Fonts and Created goofonts.com Apr 12, 2025 pm 12:02 PM

GooFonts is a side project signed by a developer-wife and a designer-husband, both of them big fans of typography. We’ve been tagging Google

Some Hands-On with the HTML Dialog Element Some Hands-On with the HTML Dialog Element Apr 16, 2025 am 11:33 AM

This is me looking at the HTML element for the first time. I&#039;ve been aware of it for a while, but haven&#039;t taken it for a spin yet. It has some pretty cool and

Multi-Thumb Sliders: General Case Multi-Thumb Sliders: General Case Apr 12, 2025 am 10:52 AM

The first part of this two-part series detailed how we can get a two-thumb slider. Now we&#039;ll look at a general multi-thumb case, but with a different and

Where should 'Subscribe to Podcast' link to? Where should 'Subscribe to Podcast' link to? Apr 16, 2025 pm 12:04 PM

For a while, iTunes was the big dog in podcasting, so if you linked "Subscribe to Podcast" to like:

See all articles