Frameworks come and go — Remix, Next, Gatsby, WordPress, Hugo, Hexo, TextPattern — but the “classic” CSS styling tactics stay. If you still use SASS and embrace the CSS inheritance — you’re probably already using this technique.
To make web design more engaging, generally, we use different page layouts. For example, our humble design tries to mix it up, switching aside
to either side, using two-column, one-third, absolutely centred layouts:
Conceptual question:
How do you target all those different layouts in CSS?
Solution
Since the source of truth in how we identify any given page is its URL, what if we split and turn it into CSS classes, breadcrumb-style?
For example, take is-language-code
package’s single-article page, https://codsen.com/os/is-language-code
— it will have the following container CSS classes:
page-os
page-os-is-language-code
page-os-is-language-code-exactly
<div class="page-os page-os-is-language-code page-os-is-language-code-exactly">
...
</div>
The playground page, one level deeper, https://codsen.com/os/is-language-code/play
, will have:
page-os
page-os-is-language-code
page-os-is-language-code-play
page-os-is-language-code-play-exactly
<div
class="page-os page-os-is-language-code page-os-is-language-code-play page-os-is-language-code-play-exactly"
>
...
</div>
And that’s for every single page on the website.
This technique, combined with creating and importing custom components, gives the 100% art direction freedom to uniquely style any page on the website. That’s a huge deal.
Remix implementation
The container div
in root.tsx
looks like this:
// ./app/root.tsx
import { useLocation } from "@remix-run/react";
// ...
let location = useLocation();
// ...
// set a container div (can be body):
<div className={pathNameToCSSClass(location.pathname)} >
and the pathNameToCSSClass()
helper function looks like this:
// ./app/utils/misc.ts
export const pathNameToCSSClass = (str: string): string => {
if (!str) {
return "";
}
if (str === "/") {
return `page-root`;
}
if (str.startsWith("/")) {
str = str.slice(1);
}
if (str.endsWith("/")) {
str = str.slice(0, -1);
}
return str
.split("/")
.map((s: string, idx: number, arr: string[]) =>
arr.reduce((acc, curr, rIdx) => {
if (rIdx > idx) {
return acc;
}
return `${acc}-${curr}`;
}, "")
)
.map((s, idx, arr) => {
// we'd produce something like ['page-os', 'page-os-email-comb']
// we need a way to identify paths exactly, so that we can
// target let's say Open Source home page ('page-os') and its children
// would not pick up its styles.
return `page${s}${arr[idx + 1] ? "" : ` page${s}-exactly`}`;
})
.join(" ");
};
This function splits the URL and reduces it into a string, prepending page-
and adding page-*-exactly
on the last segment.
Takeaway
Breadcrumb-style CSS classes on a container div give the greatest art direction freedom to uniquely CSS-style any page on the website.