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

Table of Contents
Topic Overview
Use Tailwind for theme design
Use custom properties for theme design
Handle legacy browsers
postcss-custom-properties
ie11CustomProperties
But what does this have to do with Tailwind?
Using configuration as a style guide
Summarize
Home Web Front-end CSS Tutorial Color Theming with CSS Custom Properties and Tailwind

Color Theming with CSS Custom Properties and Tailwind

Apr 01, 2025 am 04:58 AM

Color Theming with CSS Custom Properties and Tailwind

CSS custom properties not only improve code efficiency, but also create more possibilities in CSS, especially in theme design. The Atomic Smash team uses Tailwind CSS (a utility class framework). This article will explore how to use custom properties for theme design and how to integrate it with Tailwind to maximize reusability of your code. This article will not explain the introduction to Tailwind - please check the official documentation - but even if you are new to Tailwind, you may find some tips useful.

Topic Overview

Suppose we have a "CTA" component that contains the title, body, and buttons.

Writing a regular (non-Tailwind) CSS for this color scheme looks like this:

 <code>.cta { background-color: #742a2a; // 深紅色 color: #ffffff; // 白色}  .cta__heading { background-color: #e53e3e; // 中等紅色 color: #742a2a; } .cta__button { background-color: #e53e3e; }</code>

With Tailwind, we will apply these colors as utility classes in HTML:

<code><div>
<h3>Join our mailing list</h3>
<div>
<p>Get the first to know our new products</p>
  register</div>
</div></code>

I deliberately omitted classes that are not related to the basic color scheme, but you can see the full example in this demo:

Now, if we want to apply a different color scheme to our component, we need to override the color value of the original component. In the absence of Tailwind, a common approach is to attach the theme class to the component itself and redefine the color value in the cascade. So for components with the ".cta--blue" (using the BEM convention) modifier class, we will apply the CSS value of the blue color scheme:

 <code>.cta--blue { background-color: #2a4365; // 深藍(lán)色} .cta--blue .cta__heading { background-color: #3182ce; // 中等藍(lán)色 color: #2a4365; } .cta--blue .cta__button { background-color: #3182ce; }</code>

If we use Sass or other preprocessors, we can use variables to simplify our work, and we might nest .cta__heading and .cta__body selectors. It doesn't make our code more concise, but by updating these values ??in one place, it does make the code more manageable.

Now, let's say we have 10 different color schemes, like I've experienced in a project recently. Our code starts to get longer because we basically repeated the above example 10 times before changing these color values. Now imagine that each component in our design system requires 10 color schemes, and many components are much more complex than our simple CTA. Maybe our theme also needs different fonts. Suddenly, we need to write a lot of CSS.

Use Tailwind for theme design

On the other hand, if we use Tailwind, we need to change multiple classes in the HTML itself. Even if we use JavaScript frameworks (like React or Vue), this is not an easy task. To ensure unused styles are removed in production versions, Tailwind discourages the use of string concatenation to create class names (at the time of writing). So building our topics might mean adding a lot of logic to our components.

Use custom properties for theme design

By using custom properties for our color themes, we can drastically reduce the amount of code that needs to be written and reduce the maintenance burden. Let's first look at how to do this in regular CSS.

We define the custom attribute as: a variable on the root selector, making it a global variable. (The body selector also applies.) We can then use these variables to replace the color attribute value in the selector:

 <code>:root { --primary: #742a2a; // 深紅色 --secondary: #e53e3e; // 中等紅色} .cta { background-color: var(--primary); color: white; } .cta__heading { background-color: var(--secondary); color: var(--primary); } .cta__button { background-color: var(--secondary); }</code>

This is where it's really magical: Now creating code for each topic just requires updating these custom attribute values. No matter where we apply the theme class, the new value will be inherited:

 <code>.th-blue { --primary: #2a4365; // 深藍(lán)色 --secondary: #3182ce; // 中等藍(lán)色}</code>

If we want a blue color scheme, we can apply the .th-blue class to the component, and even in Use it on the tag to apply the page-wide theme and then overwrite it on individual components as needed. Using utility classes may save us more of the code writing effort than component-specific classes (such as .cta--blue in the original code), as it can be applied anywhere in our code base.

Handle legacy browsers

Like many agencies, many Atomic Smash customers still need our support for Internet Explorer 11. While I can accept progressive enhancement methods in most cases (for example, providing a simpler fallback layout for browsers that do not support CSS Grid), I found theme design to be an area that usually does not allow for easy compromises. Customers want to see their brand colors and fonts, even on older browsers. Providing a fallback with a feature query will require a lot of extra work, which will offset the benefits of using custom properties. To overcome this problem, we need a polyfill.

There are several options to provide polyfill for custom properties in IE 11.

postcss-custom-properties

The first is to use a PostCSS plugin called postcss-custom-properties. If you are already using PostCSS in your workflow, adding this plugin is fairly simple. It works by processing your CSS and outputting the result of the variable as property values. So if you have the following CSS:

 <code>:root { --color: red; } h1 { color: var(--color); }</code>

The result after processing will be:

 <code>h1 { color: red; color: var(--color); }</code>

Browsers that do not support custom properties will ignore the second rule and fall back to the regular property value. There is also an option to remove rules with custom properties from the output, so the file size will be smaller. This means no browser gets custom properties—it's a problem if you update variables dynamically—but you can use them for static values ??in your code without adverse effects.

Unfortunately, this polyfill has some limitations:

  1. You need to specify a file (or file) that defines custom properties in the configuration.
  2. Custom properties can only be defined on the :root selector.

The first limit is relatively trivial, but the second unfortunately makes this polyfill completely useless for our topic design use cases. This means we cannot redefine variables on the selector to create our topic.

ie11CustomProperties

This polyfill option involves providing client scripts instead of preprocessing CSS. We can add the following script to our head to make sure that polyfill is loading only in IE 11:

 <code>window.MSInputMethodContext && document.documentMode && document.write('');</code>

This allows us to take advantage of the custom properties as we did in the example here, so this is the solution I decided to use. It has a limitation that custom properties set in the style attribute will not be polyfilled. But I've tested it against the above topic design example and it works fine.

But what does this have to do with Tailwind?

As we have seen, utility classes—one-purpose classes that can be applied anywhere in HTML—can make our code more reusable. This is the main selling point of Tailwind and other utility class frameworks – the size of the CSS file you deliver will eventually become smaller as a result. Tailwind provides multiple color classes: .bg-red-medium will give us the red background-color property value, .text-red-medium is for color, and so on, for border, box-shadow, or anywhere you can think of where color values ??may be needed.

Colors can be defined in the configuration file:

 <code>module.exports = { theme: {  colors: {   red: {    medium: '#e53e3e',    dark: '#742a2a'   },   blue: {    medium: '#3182ce',    dark: '#2a4365'   }  } } }</code>

If we want to use custom property values ??for our Tailwind class, we can specify them in the configuration:

 <code>module.exports = { theme: {  colors: {   'th-primary': 'var(--primary)',   'th-secondary': 'var(--secondary)'  } } }</code>

I prefixed the subject-related class names so it's obvious that they are particularly relevant to the subject design, but you can feel free to use any convention that suits you.

Now we can use these classes through Tailwind. Using .bg-th-primary is equivalent to writing:

 <code>.some-element { background-color: var(--primary); }</code>

In our CSS we can define custom properties of the theme as before:

 <code>:root { --primary: #742a2a; --secondary: #742a2a; } .th-blue { --primary: #2a4365; --secondary: #3182ce; }</code>

Let's apply these classes to our HTML. The first example provides us with a component with a default theme (variables defined on :root). The second has our blue theme. The only difference is that the .th-blue class was added to the component. (For simplicity and clarity, I omitted classes that are not related to the topic.)

<code><div class="bg-th-primary text-white">
<h3 class="bg-th-secondary text-th-primary">Join our mailing list</h3>
<div>
<p>Get the first to know our new products</p>
<button class="bg-th-secondary">register</button>
</div>
</div>
?
<div class="th-blue bg-th-primary text-white">
<h3 class="bg-th-secondary text-th-primary">Join our mailing list</h3>
<div>
<p>Get the first to know our new products</p>
<button class="bg-th-secondary">register</button>
</div>
</div></code>

Using configuration as a style guide

Tailwind encourages you to define all variables in your configuration, and personally, I agree that this is a better approach. This means that the configuration file can be a single source of fact, rather than (probably) ending up with multiple places to define the color and other theme values. Fortunately, we can also use the values ??in the Tailwind configuration file for our custom properties. We need to first define all colors in the configuration (assuming we don't use the default palette included by Tailwind):

 <code>module.exports = { theme: {  colors: {   red: {    medium: '#e53e3e',    dark: '#742a2a'   },   blue: {    medium: '#3182ce',    dark: '#2a4365'   },   'th-primary': 'var(--primary)',   'th-secondary': 'var(--secondary)'  } } }</code>

Then we can access the theme object in CSS:

 <code>:root { --primary: theme('colors.red.dark'); --secondary: theme('colors.red.medium'); } .th-blue { --primary: theme('colors.blue.dark'); --secondary: theme('colors.blue.medium'); }</code>

Summarize

I'm so happy to be able to use custom properties without worrying about browser support, and I'm even more happy to be able to integrate it seamlessly with our existing workflows. It's hard to exaggerate the time they will save us in terms of theme design. I hope that even if you are not a Tailwind user, this article may encourage you to try custom properties for this use case.

The above is the detailed content of Color Theming with CSS Custom Properties and Tailwind. 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.

Case Sensitivity in CSS: Selectors, Properties, and Values Explained Case Sensitivity in CSS: Selectors, Properties, and Values Explained Jun 19, 2025 am 12:38 AM

CSSselectorsandpropertynamesarecase-insensitive,whilevaluescanbecase-sensitivedependingoncontext.1)Selectorslike'div'and'DIV'areequivalent.2)Propertiessuchas'background-color'and'BACKGROUND-COLOR'aretreatedthesame.3)Valueslikecolornamesarecase-insens

See all articles