Day 67 - Avoid Custom Properties in Shorthands

Day 67 - Avoid Custom Properties in Shorthands

?? An Awesome CSS Link a Day – Day 67 ??

Why You Should Avoid Custom Properties in Shorthands

#AnAwesomeCSSLinkADay #YouDontMessWithCSS #CSS

Custom properties (--var) are a powerful feature in CSS, enabling dynamic styling and reusability. However, using them inside shorthand properties can lead to unexpected behavior and limit the flexibility of CSS defaults.

Introduction

Shorthand properties in CSS, like margin, padding, background, and border, reset all unspecified values to their defaults. When a custom property is used in a shorthand, any missing values become initial, potentially breaking styles. Understanding this issue helps maintain robust and predictable CSS.

?? The Issue: Invalid Custom Properties in Shorthands

Custom properties cannot hold complex shorthand values like "10px solid black". If they are used within a shorthand but evaluate to an invalid value, the entire declaration is ignored or resets unexpectedly.

Example of the Problem

:root { --main-border: solid; }

.box {
  border: 2px var(--main-border) black; /* this breaks if --main-border is invalid */
}        

If --main-border is not defined or incorrectly formatted, the entire border declaration fails. A safer approach is to set individual properties instead:

:root { --main-border: solid; }

.box { 
  border-width: 2px; 
  border-style: var(--main-border, solid); 
  border-color: black;
}        

This way, each property remains functional even if the custom property is missing.

?? Today’s Link

For a deep dive into this topic, check out this great article by Manuel Matuzovi?:

?? Maybe don't use custom properties in shorthands

?? Giveaways

  • Learn why shorthands reset unspecified values, making them fragile with custom properties.
  • Discover how fallbacks can prevent unexpected styling issues.
  • Master best practices for using CSS variables without breaking styles.

? Why This Rocks

  • Helps avoid unintended style resets caused by shorthand behavior.
  • Ensures greater flexibility by keeping CSS more modular and predictable.
  • Teaches best practices for using custom properties effectively.

??? Join the Conversation

  • Have you encountered issues when using CSS variables in shorthands?
  • Do you prefer using individual properties over shorthand declarations?
  • What’s your approach to fallback values when working with custom properties?

Let’s refine our CSS skills together! ??

要查看或添加评论,请登录

Emiliano Pisu的更多文章

社区洞察