Context
Context describes the context of a Component or Child.
<ul class="main-menu">
<li class="main-menu_item">
<a class="main-menu_link" aria-current="page"></a> <!-- Context -->
</li>
</ul>
.main-menu_link {
/* styles */
&[aria-current="page"] {
/* styles */
}
}
Context means circumstance, not appearance. These circumstances are typically:
- State: A transient property of a component. It is “active”, for example.
- Metadata: Similar to state, but could be persistent. For example, how many items are in a list.
- Parent: A component that is a parent (at any level) of the component in question. So, if this component is in a sidebar, for example.
- Media: The screen size, orientation etc of the device.
State example
<ul class="main-menu">
<li class="main-menu_item">
<a class="main-menu_link" aria-current="page"></a> <!-- State -->
</li>
<li class="main-menu_item">
<a class="main-menu_link"></a>
</li>
</ul>
.main-menu_link {
/* styles */
&[aria-current="page"] {
/* styles for main-menu_link, when it is current page */
}
}
Metadata example
<ul class="main-menu" data-count="2"> <!-- Metadata -->
<li class="main-menu_item">
<a class="main-menu_link"></a>
</li>
<li class="main-menu_item">
<a class="main-menu_link"></a>
</li>
</ul>
.main-menu {
/* styles */
&[data-count="2"] {
/* styles for main-menu, when it contains two items */
}
}
Parent example
<div class="home-page"><!-- Parent -->
<ul class="main-menu">
<li class="main-menu_item">
<a class="main-menu_link"></a>
</li>
<li class="main-menu_item">
<a class="main-menu_link"></a>
</li>
</ul>
</div>
.main-menu {
/* styles */
@nest .home-page & {
/* styles for main-menu, when it is within the home page */
}
}
Multiple contexts
Multiple contexts are added to a single code block.
.main-menu {
/* styles */
&[data-count="2"] {
/* styles for main-menu, when it contains two items */
}
@nest .home-page & {
/* styles for main-menu, when it is within the home page */
}
@media (min-width: 600px) {
/* styles for main-menu, on a screen at least 600px wide */
}
}
Naming
When possible, state, and metadata should be handled with attribute selectors. This helps give a distinct syntax for Context, and provides consistency with ARIA. If for some reason, you need to use a class for state or metadata, it should be constructed using an attribute, two hyphens, and a value. For example active--true
or transition--enter
.
Considerations
Context makes use of specificity to override existing styles. With this power comes responsibility. If you find your CSS is getting complicated, a new Component might make more sense than a parent context.