The beauty of CSS mixins
CSS mixins are a new construct in CSS that allow you to define a named piece of code that can be reused throughout a stylesheet. A mixin is similar to a custom property or CSS function, but it can return multiple values at once. Instead of defining a single value like background: red; color: white; border-radius: 2px;, a mixin can return all of those values together. Microsoft is working on implementing mixins in Chromium-based browsers, and they are very close to being ready for widespread use.
To define a mixin, you use the @mixin rule, and to apply it, you use the @apply rule. Mixin names start with two dashes, like custom properties. Once defined, a mixin can be reused anywhere in your stylesheet, just like a piece of CSS code written directly in the element's style block.
Mixins can also accept parameters, with optional types and default values. This allows you to create reusable components that can be customized for different elements. Additionally, mixins can hold conditional rules, such as @media, @supports, and @container, making them even more versatile. For example, you can create a mixin that applies styles conditionally based on the viewport size.
Another powerful feature of mixins is the ability to accept a block of CSS from the call site using the @contents rule. This allows you to pass additional declarations or custom styles when using the mixin, giving you more flexibility in your design. Mixins can also have private variables, which are not accessible to the element applying the mixin.
The potential use cases for mixins are extensive. For example, they can be used to define styles that only apply in dark mode, or to create responsive design breakpoints with named breakpoints. In a white-label website scenario, mixins can allow customers to customize the theme while keeping the original HTML and CSS untouched. This approach offers a balance between control and customization, giving you the best of both worlds.
Rewritten by urgent.news; may contain errors — check the original.
Source: patrickbrosset.com