Home - VSADX/scoped-css GitHub Wiki

Scoped CSS basics:

  • add \& before any CSS selector to scope it
  • add class="scoped" to a <style> element to enable scoping
  • Scoped CSS looks at the parent element of the <style>
<header>
    <a> Home </a>
    <nav>
        <a> Previous work </a>
        <a> About us </a>
        <a> Contact </a>
    </nav>

    <style class="scoped">
      \& {
        display: grid;
        grid-template-columns: 1fr 3fr;
      }
      \& > a {
        color: white;
        font-size: 2em;
      }
      \& > nav > a {
        color: dodgerblue;
      }
    </style>
</header>

How does Scoped CSS help write faster?

You write your CSS at the same time as the HTML, in the same area, in the same file. It not only helps you create faster, it helps you equally as much when you come back later! Scoped CSS lets you have HTML that is more concise by using CSS classes for truly reusable styles.

How can I maintain less class names?

Scoped CSS gives you an entry point into your HTML, but you still might be forced into creating classes you don't want. What can you do? Use the > selector in CSS. It's native to CSS; it says, "Only select a direct child please! Do not select all <p>."

\& p { color: blue; }       /* all scoped <p> */

\& > p { color: red; }      /* only direct children <p> */

Is there a place for reusable CSS classes?

There is! Scoped CSS is can help authors, designers, or maintainers but it helps the most when used together traditionally. Reusable classes might be basic layouts like .flex-center or something specific to your website. See the wiki sidebar for a post on reusable CSS.

Will this make it harder to maintain?

Not even a little, Scoped CSS was once part of browsers already! It is builtin to the most popular web frameworks, web designers can use this tool to help them write faster, but also - maintain CSS easier. How?

When CSS is tied to HTML it can result in beautiful, highly-unique designs. It's maintaining that CSS which is most challenging.

  1. Scoped CSS allows for CSS to be placed directly beside the HTML using it.
  2. You can create as many CSS insertion points as needed.
  3. The > selector can dial in the level of scoping for your needs.
  4. Any time you change the HTML you won't need to look for the corresponding CSS.
⚠️ **GitHub.com Fallback** ⚠️