Get in touch

I will reply within 1 business day.

Working with scope

cssjavascript

The rise of component based web development has long been the driving force behind many web technologies. Let's take a look at some of the latest techniques in scoping styles.

Scoping to a node

As we all know naming things is hardest part of web development.

<my-scoped-component>
    <style>
        @scope (my-scoped-component) {
            :scope {
                background-color: red;
            }
        }
    </style>
</my-scoped-component>

By nesting our scope in a style tag we can use the & selector to reference the parent html removing the need for a class.

Handling inheritance

Whilst using custom properties it can be very tempting to initalise them inside a component's class however this will mean it's available to child elements which can be problematic. Luckily we can control variable inheritance with @property.

@property --layout-columns-xs {
  syntax: "*";
  inherits: false;
  initial-value: [full-start] minmax(0, 1fr) [breakout-start] 0 [content-start]
    repeat(1, 21rem) [content-end] 0 [breakout-end] minmax(0, 1fr) [full-end];
}

@property --layout-columns-xl {
  syntax: "*";
  inherits: false;
  initial-value: [full-start] minmax(0, 1fr) [breakout-start] 0 [content-start]
    repeat(6, 10rem) [content-end] 0 [breakout-end] minmax(0, 1fr) [full-end];
}

page-layout {
  display: grid;
  grid-template-columns: var(--layout-columns-xs);

  @media screen and (width >= 1480px) {
    grid-template-columns: var(--layout-columns-xl);
  }
}