国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Implementing more DRY code using preprocessor
More than one topic? no problem!
Home Web Front-end CSS Tutorial A DRY Approach to Color Themes in CSS

A DRY Approach to Color Themes in CSS

Mar 26, 2025 am 09:55 AM

A DRY Approach to Color Themes in CSS

Recently, Florens Verschelde asked how to define dark mode styles in class and media queries while avoiding repeated declaration of CSS custom properties. I've also encountered this problem in the past, but haven't found a suitable solution.

Our goal is to avoid redefining—and thus repeating—customizing properties when switching light and dark mode. This is the goal of DRY (Don't Repeat Yourself) programming, but the typical pattern of switching topics is usually like this:

 <code>:root { --background: #fff; --text-color: #0f1031; /* etc. */ } @media (prefers-color-scheme: dark) { :root { --background: #0f1031; --text-color: #fff; /* etc. */ } }</code>

Do you understand what I mean? Of course, it may not seem important in this short example, but imagine dealing with dozens of custom properties at once – it’s a lot of repetition!

Then I remembered the trick of using --var: ; , and although I didn't think of it at first, I found a way to make it work: instead of using var(--light-value, var(--dark-value)) or similar nested combinations, use them side by side!

Of course, there must be someone who discovered this before me, but I haven't heard of using (or rather, abused) CSS custom properties to achieve this. Without further ado, this is the idea:

 <code>--color: var(--light, orchid) var(--dark, rebeccapurple);</code>

If the --light value is set to initial , the fallback value (orchid) will be used, which means that --dark should be set to a space character (this is a valid value), making the final calculated value look like this:

 <code>--color: orchid ; /* 注意額外的空格*/</code>

Instead, if --light is set to space and --dark is set to initial , we end up with a calculated value as:

 <code>--color: rebeccapurple; /* 同樣,注意空格*/</code>

Now, this is fine, but we need to define --light and --dark custom properties based on context. Users can set system preferences (light or dark), or use certain UI elements to switch the theme of the website. Just like the Florens example, we will define these three cases and use Lea's proposed "on" and "off" constants for some small readability enhancements to make it clear at a glance:

 <code>:root { /* 感謝Lea Verou!*/ --ON: initial; --OFF: ; } /* 默認(rèn)情況下,淺色主題處于啟用狀態(tài)*/ .theme-default, .theme-light { --light: var(--ON); --dark: var(--OFF); } /* 默認(rèn)情況下,暗色主題處于禁用狀態(tài)*/ .theme-dark { --light: var(--OFF); --dark: var(--ON); } /* 如果用戶偏好暗色,那么他們將獲得暗色主題*/ @media (prefers-color-scheme: dark) { .theme-default { --light: var(--OFF); --dark: var(--ON); } }</code>

We can then set all the topic variables in one declaration without duplication. In this example, theme-* class is set to html element, so we can use :root as selector, just like many people like to do, but if the cascading properties of custom properties make more sense, you can also set them to body .

 <code>:root { --text: var(--light, black) var(--dark, white); --bg: var(--light, orchid) var(--dark, rebeccapurple); }</code>

To use them, we use var() and built-in fallback because we like to be careful:

 <code>body { color: var(--text, navy); background-color: var(--bg, lightgray); }</code>

Hopefully you've started to see the benefits here. Rather than defining and switching a large number of custom properties, we process two properties and set all other properties only once on :root . This is a huge improvement from where we started.

Implementing more DRY code using preprocessor

If I were to look at the following line of code out of context, I would definitely be confused because the color is a single value, not two!

 <code>--text: var(--light, black) var(--dark, white);</code>

That's why I prefer to be a little abstract. We can set up a function using our favorite preprocessor (Sass in my case). If we keep the code with --light and --dark values ??defined above in different contexts, we just need to change the actual custom attribute declaration. Let's create a light-dark function that returns us the CSS syntax:

 @function light-dark($light, $dark) {
  @return var(--light, #{ $light }) var(--dark, #{ $dark });
}

We will use it like this:

 :root {
   --text: #{ light-dark(black, white) };
   --bg: #{ light-dark(orchid, rebeccapurple) };
   --accent: #{ light-dark(#6d386b, #b399cc) };
}

You will notice that there is an interpolation separator #{ … } around the function call. Without these, Sass will output the code as is (just like a normal CSS function). You can try various implementations, but the syntax complexity depends on your preferences.

How does this look for a more DRY code base?

More than one topic? no problem!

You can do this with more than two modes. The more topics you add, the more complex it will be to manage, but the key is that this is possible ! We add another group of ON or OFF variables topics and set an extra variable in the value list.

 <code>.theme-pride { --light: var(--OFF); --dark: var(--OFF); --pride: var(--ON); } :root { --text: var(--light, black) var(--dark, white) var(--pride, #ff8c00) ; /* 換行符是完全有效的*/ /* 其他要聲明的變量… */ }</code>

Is this a skill? Yes, absolutely. Is this a good use case for potential, non-existent CSS booleans? OK, this is a dream.

And you? Have you solved this problem in a different way? Please share in the comments!

The above is the detailed content of A DRY Approach to Color Themes in CSS. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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 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)

What is 'render-blocking CSS'? What is 'render-blocking CSS'? Jun 24, 2025 am 12:42 AM

CSS blocks page rendering because browsers view inline and external CSS as key resources by default, especially with imported stylesheets, header large amounts of inline CSS, and unoptimized media query styles. 1. Extract critical CSS and embed it into HTML; 2. Delay loading non-critical CSS through JavaScript; 3. Use media attributes to optimize loading such as print styles; 4. Compress and merge CSS to reduce requests. It is recommended to use tools to extract key CSS, combine rel="preload" asynchronous loading, and use media delayed loading reasonably to avoid excessive splitting and complex script control.

External vs. Internal CSS: What's the Best Approach? External vs. Internal CSS: What's the Best Approach? Jun 20, 2025 am 12:45 AM

ThebestapproachforCSSdependsontheproject'sspecificneeds.Forlargerprojects,externalCSSisbetterduetomaintainabilityandreusability;forsmallerprojectsorsingle-pageapplications,internalCSSmightbemoresuitable.It'scrucialtobalanceprojectsize,performanceneed

Does my CSS must be on lower case? Does my CSS must be on lower case? Jun 19, 2025 am 12:29 AM

No,CSSdoesnothavetobeinlowercase.However,usinglowercaseisrecommendedfor:1)Consistencyandreadability,2)Avoidingerrorsinrelatedtechnologies,3)Potentialperformancebenefits,and4)Improvedcollaborationwithinteams.

CSS Case Sensitivity: Understanding What Matters CSS Case Sensitivity: Understanding What Matters Jun 20, 2025 am 12:09 AM

CSSismostlycase-insensitive,butURLsandfontfamilynamesarecase-sensitive.1)Propertiesandvalueslikecolor:red;arenotcase-sensitive.2)URLsmustmatchtheserver'scase,e.g.,/images/Logo.png.3)Fontfamilynameslike'OpenSans'mustbeexact.

What is Autoprefixer and how does it work? What is Autoprefixer and how does it work? Jul 02, 2025 am 01:15 AM

Autoprefixer is a tool that automatically adds vendor prefixes to CSS attributes based on the target browser scope. 1. It solves the problem of manually maintaining prefixes with errors; 2. Work through the PostCSS plug-in form, parse CSS, analyze attributes that need to be prefixed, and generate code according to configuration; 3. The usage steps include installing plug-ins, setting browserslist, and enabling them in the build process; 4. Notes include not manually adding prefixes, keeping configuration updates, prefixes not all attributes, and it is recommended to use them with the preprocessor.

What are CSS counters? What are CSS counters? Jun 19, 2025 am 12:34 AM

CSScounterscanautomaticallynumbersectionsandlists.1)Usecounter-resettoinitialize,counter-incrementtoincrease,andcounter()orcounters()todisplayvalues.2)CombinewithJavaScriptfordynamiccontenttoensureaccurateupdates.

CSS: When Does Case Matter (and When Doesn't)? CSS: When Does Case Matter (and When Doesn't)? Jun 19, 2025 am 12:27 AM

In CSS, selector and attribute names are case-sensitive, while values, named colors, URLs, and custom attributes are case-sensitive. 1. The selector and attribute names are case-insensitive, such as background-color and background-Color are the same. 2. The hexadecimal color in the value is case-sensitive, but the named color is case-sensitive, such as red and Red is invalid. 3. URLs are case sensitive and may cause file loading problems. 4. Custom properties (variables) are case sensitive, and you need to pay attention to the consistency of case when using them.

What is the conic-gradient() function? What is the conic-gradient() function? Jul 01, 2025 am 01:16 AM

Theconic-gradient()functioninCSScreatescirculargradientsthatrotatecolorstopsaroundacentralpoint.1.Itisidealforpiecharts,progressindicators,colorwheels,anddecorativebackgrounds.2.Itworksbydefiningcolorstopsatspecificangles,optionallystartingfromadefin

See all articles