r/css • u/osmium_2259 • 3d ago
Article Styling a component with inline scoped CSS
When building a demo project, I learned about CSS scoping and nesting. In particular, I learned about using the @scope at-rule in inline <style> tags, allowing you to restrict the styles to the <style> tag's parent element, whether that's a <button> or a <div>, you name it.
This, combined with nesting allowed me to style my whole component with very few class selectors, which I thought was pretty slick!
Here's a sample (Django template) from the demo:
<aside class="sidebar" tabindex="-1">
{# lines omitted for brevity #}
<div>
<style>
@scope {
ul {
margin: 0;
padding: 0;
font-size: 18px;
}
li a {
display: block;
transition: all .2s;
cursor: pointer;
border-bottom: 1px solid rgb(from var(--primary-color) r g b / 20%);
padding: 20px 16px;
}
li:last-of-type a {
border-bottom-color: transparent;
}
li a:is(.active, :hover, :focus) {
border-bottom-color: var(--primary-color);
background-color: var(--primary-color);
color: white;
}
li i {
margin-right: 8px;
}
}
</style>
<ul>
{% for name, url, icon_class, active in links %}
<li>
<a href="{{ url }}" class="{% if active %}active{% endif %}">
<i class="bi {{ icon_class }}"></i> {{ name }}
</a>
</li>
{% endfor %}
</ul>
</div>
{# lines omitted for brevity #}
</aside>For those interested, my demo is a Django project using a sidebar component to showcase the concept of creating components with Django's inclusion_tag and make the component template self-contained (e.i., HTML, CSS, JS in one file).
Curious if any of you have used inline scoped CSS like this? I'm uncertain how practical it is, but I think it is very interesting at any rate!
MDN @scoped docs: https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@scope
Demo repo: https://github.com/osmium2259/django_builtin_components_demo
2
u/Evgenii_Korolev 2d ago
it's nice for one-off components, but if that sidebar ever renders more than once you ship the same style block per instance, so for anything repeated i'd move it to the stylesheet as
@scope (.sidebar) { ... }and keep the same nesting. one gotcha: @scope itself adds no specificity, and when two scopes fight the closer root wins before source order does, which can be confusing to debug. browser support is pretty recent too, so check caniuse if you need older browsers.