architecture – CSS-Tricks https://css-tricks.com Tips, Tricks, and Techniques on using Cascading Style Sheets. Thu, 21 Oct 2021 15:37:33 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 https://i0.wp.com/css-tricks.com/wp-content/uploads/2021/07/star.png?fit=32%2C32&ssl=1 architecture – CSS-Tricks https://css-tricks.com 32 32 45537868 Kubernetes Explained Simply: Containers, Pods and Images https://css-tricks.com/kubernetes-explained-simply-containers-pods-and-images/ https://css-tricks.com/kubernetes-explained-simply-containers-pods-and-images/#comments Mon, 05 Jul 2021 14:17:33 +0000 https://css-tricks.com/?p=343166 If you zone out every time someone mentions “Kubernetes,” “containers,” or “pods,” this article is for you. No complex diagrams involved!

As a front-end developer, you don’t have to know how to configure an infrastructure from scratch. However, if you …


Kubernetes Explained Simply: Containers, Pods and Images originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
If you zone out every time someone mentions “Kubernetes,” “containers,” or “pods,” this article is for you. No complex diagrams involved!

As a front-end developer, you don’t have to know how to configure an infrastructure from scratch. However, if you have a basic understanding of how it works, you can deploy and rollback your applications more independently while also being more informed during conversations about this topic.

Let’s start with web searching what Kubernetes is.

Kubernetes is an open-source container-orchestration system for automating computer application deployment, scaling, and management.

Wikipedia

OK, but what is a container?

Simply put, a container is like a virtual computer that you can create, use, destroy and reboot remotely.

Now imagine this computer is actually in a cloud, running alongside thousands of other virtual computers. And all of this runs in a real computer which is powerful as heck. Your computer is now a container in the cloud.

An illustrated cloud with five computers, each labeled “Container”.

But wait — how will you create and control this virtual computer? How will it communicate with other computers in the same cloud? And how will it communicate with the world? Sounds like you need a way to orchestrate all of this. Hence: our maestro, Kubernetes (or K8s for short)!

A cloud with five computers labeled “Container” and a maestro below it labeled “K8s”

You may have also heard the term pods. What are those, and where do they fit here? Well, simply put, pods are groups of one or more containers. They are the smallest deployable unit in K8s, like an atom.

Imagine you’re building a WordPress website and you need a computer running PHP and a MySQL database. Running both in the same computer might be too heavy; so you could instead create one container for PHP, one for MySQL, and K8s will help make them communicate.

Then, you’d group these two containers in a pod, which represents the entire application. That means you can now start and kill an entire application through pods.

Cloud with circle inside it labeled “Pod” and two computers inside it each labeled “PHP” and “MySQL”

You would likely not create just one pod alone to deploy an app in production, though — there‘s more that we don’t need to cover right now, but you can read more about pods in the K8s documentation.

Now’s a good time to ask: what happens when you deploy an app in this setup?

K8s creates a new pod, redirects the traffic to it, and when it‘s sure everything‘s working, it kills the old pod. Again, more entities are involved to control and redirect requests, but we’re leaving that out today.

However, sometimes the deploy breaks something and we have to rollback our application to the previous version. Imagine everything’s on fire, and we have to start all of those computers from scratch — install Linux, Node, Git, clone the repository, install dependencies, build the app… that would take forever! If only there was a faster way, like taking a snapshot from the past to quickly restore everything to…

USB flash drive labeled “June 15 2:45pm”

Enter: images! You probably have heard this term a lot too. An image is like a backup of a container with everything already installed and configured. A new image is generated with your Continuous Integration (abbr>CI) every time you push to the main branch of your repository, and it‘s then replicated into new containers when they’re created.

And what are they good for? Well, mainly two things: the first one is restoring to the previous image quickly, like our example above. But they‘re also useful when your website has a bunch of traffic and just one computer won’t be able to handle it.

When you have an image, you can create as many identical containers as you want and replicate that image across all of them, serving the exact same contents.

Four computers all equally labeled “Commit d406cht”

All done! We just covered the basics on how the infrastructure of an application works, and now hopefully you can extrapolate into whatever tools your project is using.


Many thanks to Eduardo Shiota for enabling me to explain this!


Kubernetes Explained Simply: Containers, Pods and Images originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/kubernetes-explained-simply-containers-pods-and-images/feed/ 11 343166
Reconciling Editor Experience and Developer Experience in the CMS https://css-tricks.com/reconciling-editor-experience-and-developer-experience-in-the-cms/ https://css-tricks.com/reconciling-editor-experience-and-developer-experience-in-the-cms/#comments Fri, 12 Feb 2021 15:56:47 +0000 https://css-tricks.com/?p=333833 Components are great, aren’t they? They are these reusable sources of truth that you can use to build rock-solid front-ends without duplicating code.

You know what else is super cool? Headless content management! Headless content management system (CMS) products offer …


Reconciling Editor Experience and Developer Experience in the CMS originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
Components are great, aren’t they? They are these reusable sources of truth that you can use to build rock-solid front-ends without duplicating code.

You know what else is super cool? Headless content management! Headless content management system (CMS) products offer a content editing experience while freeing that content in the form of data that can be ported, well, to any API-consuming front-end UI. You can structure your content however you’d like (depending on the product), and pull that content into your front-end applications.

Using these two things together — a distributed CMS solution with component-based front-end applications — is a core tenet of the Jamstack.

But, while components and headless CMSs are great on their own, it can be difficult to get them to play nicely together. I‘m not saying it‘s difficult to hook one up to the other. In a lot of cases, it’s actually quite painless. But, to craft a system of components that is reusable and consistent, and to have that system maintain parity with a well-designed CMS experience is a difficult thing to achieve. It’s that win-win combo of being able to freely write content and then have that content structured into predictable components that makes headless content management so appealing.

Achieving parity between a CMS and front-end components

My favorite demonstrating this complexity is a simple component: a button. Let‘s say we’re working with React to build components and our button looks like this:

<Button to="/">Go Home</Button>

In the lovely land of React, that means the <Button> component has two props (i.e. properties, attributes, arguments, etc.) — to and children. children is a React thing that holds all the content within the opening and closing tags, which is “Go Home” in this case.)

If we’re going to enable users in the content editor to add buttons to the site, we want a system for them that makes it easy to understand how their actions in the CMS affect what appears on screen in the front-end app. But we also want our developer(s) to work productively with component properties that make sense to them and within the framework they’re working (i.e. React in our example).

How do we do that?

We could…

…use fields in the CMS that match the components’ properties, though I’ve had little success with this approach. to and children don‘t make much sense to content editors trying to build a button. Believe me, I‘ve tried. I‘ve tried with beginners and experienced editors alike. I‘ve tried helper text. It doesn’t matter. It’s confusing.

What makes more sense is using words editors are more likely to understand, like label or text for children and url for to.

Showing a mockup of CMS text input fields for a button component, one for a to field with https as a placeholder, and another for children with Buy Now as a placeholder.
😕
Showing a mockup of CMS text input  fields for a button component, one for a URL field with https as a placeholder, and another for Button Label with Buy Now as a placeholder.
🤓

But then we’d be out of sync with our code.

Or what if we…

masked attributes in the CMS. Most headless CMS solutions enable you to have a different value for the label of the field than the name that is used when delivering content via an API.

We could label our fields Label and URL, but use children and to as the names. We could. But we probably shouldn’t. Remember what Ian Malcolm said?

On the surface, masking attributes makes sense. It’s a separation of concerns. The editors see something that makes them happy and productive, and the developers work with the names that make sense to them. I like it, but only in theory. In practice, it confuses developers. Debugging a content editor issue often requires digging through extra layers (i.e. time) to find the relationship between labels and field names.

Or why not …

…change the properties. Wouldn’t it be easier for developers to be flexible? They’re the ones designing the system, after all.

Yes, that’s true. But if you follow that rule exclusively, it’s inevitable that you’re going to run into some issue along the way. You’ll likely end up fighting against the framework, or props will just feel goofy.

In our example, using label and url as props for a button works totally fine for data that originates from the CMS. But that also means that any time our developers want to use a button within the code, it looks like this:

<Button label="Go Home" url="/" />

That may seem okay on the surface, but it significantly limits the power of the button. Let’s say I want to support some other feature, like adding an icon within the label. I’m going to need some additional logic or another property for it. If I would have used React’s children approach instead, it would have just worked (likely after some custom styling support).

Okay, so… what do we do?

Introducing transformers

The best approach I’ve found is to separately optimize the editor and developer experiences. Craft a CMS experience that is catered to the editors. Build a codebase that is easy for developers to navigate, understand, and enhance.

The result is that the two experiences will not be in parity with one another. We need some set of utilities to transform the data from the CMS structure into something that can be used by the front-end, regardless of the framework and tooling you’re using.

I call these utilities transformers. (Aren’t I so good at naming things!?) Transformers are responsible for consuming data from your CMS and transforming it into a shape that can be easily consumed by your components.

Illustration showing a rounded square that says Data Source pointing to a yellow box that says transformer, pointing to another rounded square that says component. There is a small code snippet on both sides of the yellow square showing how it transforms the Label and URL fields to Children and To, respectively.

While I‘ve found that transforming data is the smoothest means to get great experiences in both the CMS and the codebase, I don‘t have an obvious solution for how (or perhaps where) those transformations should happen. I‘ve used three different approaches, all of which have their pros and cons. Let’s take a look at them.

1. Alongside components

One approach is to put transformers right alongside the components they are serving. This is the approach I typically take in organizing component-based projects — to keep related files close to one another.

The same illustrated diagram, but the yellow box is now the button index.js file that points to a transformer.js file that then points to a button component.js file.

That means that I often have a directory for every component with a predictable set of files. The index.js acts as the controller for the component. It is responsible for importing and exporting all other relevant files. That makes it trivial to wrap the component with some logic-based behavior. In other words, it could transform properties of the component before rendering it. Here’s what that might look like for our button example:

import React from "react"

import Component from "./component"
import transform from "./transformer"

const Button = props => <Component {...transform(props)} />

export default Button

The transform.js file might look like this:

export default input =&gt; {
  return {
    ...input,
    children: input.children || input.label,
    to: input.to || input.url
  }
}

In this example, if to and children were properties sent to the component, it works just fine! But if label and url were used instead, they are transformed to children and to. That means the <Button> component (component.js) only has to worry about using children and to.

const Button = ({ children, to }) => <a href={to}>{children}</a>

I personally love this approach. It keeps the logic tightly coupled with the component. The biggest downside I‘ve found thus far is that it’s a large number of files and transforms, when the entire dataset for any given page could be transformed earlier in the stack, which would be…

2. At the top of the funnel

The data has to be pulled into the application via some mechanism. Developers use this mechanism to retrieve as much data for the current page or view as possible. Often, the fewer number of queries/requests a page is required to make, the better its performance.

In other words, that mechanism often exists near the top of the funnel (or stack), as opposed to each component pulling its own data in dynamically. (When that’s necessary, I use adapters.)

Another illustration, this time where the yellow box is labeled import mechanism, and it has three arrows, each pointing to a white square, labeled, component 1, component 2, and component 3, respectively.

The mechanism that retrieves the page data could also be responsible for transforming all the data for the given page before it renders any of its components.

In theory, this is a better approach than the first one. It decreases the amount of work the browser has to do, which should improve the front-end performance. That means the server has to do more work, but that’s often a better choice.

In practice, though, this is a lot of work. Data structures can be big, complex, and interwoven. It can take a heck of a lot of work to transform everything into the right format at the top of the funnel, and then pass the transformed data down to components. It’s also more difficult to test because of the potential complexity and variation of the giant data blob retrieved at the top of the stack. With the first approach, testing the transformer logic for the button is trivial. With this approach, you’d want to account for transforming button data anywhere that it might appear in the retrieved data object.

But, if you can pull it off, this is generally the better approach.

3. The middleman engine

The third and final (and magical) approach is to do all this work somewhere else. In this case, we could build an engine (i.e. a small application) that would do the transformations for us, and then make the content available for the application to consume.

Another illustration, this time where the yellow box is the abstracted data source, which points to a white box labeled import mechanism, which then points to the same three white squares representing components that are outlined in the previous illustration.

This is likely even more work than the second approach. And it has added cost and maintenance in running an additional application, which takes more effort to ensure it is rock solid.

The major upside to this approach is that we could build this as an abstracted engine. In other words, any time we bring in data to any front-end application, it goes through this middleman engine. That means if we have two projects that use the same CMS or data source, our work is cut down significantly for the second project.


If you aren‘t doing any of this today and want to start, my advice is to treat these approaches like stepping stones. They grow in complexity and maintenance and power as the application grows. Start with the first approach and see how far that gets you. Then, if you feel like you could benefit from a jump to the second, do it! And if you’re feeling like living dangerously, go for the third!

In the end, what matters most is crafting an experience that both your editors and your developers understand and enjoy. If you can do that, you win!


Reconciling Editor Experience and Developer Experience in the CMS originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/reconciling-editor-experience-and-developer-experience-in-the-cms/feed/ 2 333833
Tech Stacks and Website Longevity https://css-tricks.com/tech-stacks-and-website-longevity/ https://css-tricks.com/tech-stacks-and-website-longevity/#comments Mon, 25 Jan 2021 21:41:12 +0000 https://css-tricks.com/?p=333020 Steren Giannini in “My stack will outlive yours”:

My stack requires no maintenance, has perfect Lighthouse scores, will never have any security vulnerability, is based on open standards, is portable, has an instant dev loop, has no build step


Tech Stacks and Website Longevity originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
Steren Giannini in “My stack will outlive yours”:

My stack requires no maintenance, has perfect Lighthouse scores, will never have any security vulnerability, is based on open standards, is portable, has an instant dev loop, has no build step and… will outlive any other stack.

Jeremy Keith in “npm ruin dev”:

Instead of reaching for all-singing all-dancing toolchain by default, I’m going to start with a boring baseline. If and when that becomes too painful or unwieldy, then I’ll throw in a task manager. But every time I add a dependency, I’ll be limiting the lifespan of the project.

I like both of those sentiments.

Steren’s “stack” is HTML and CSS only. Will HTML and CSS “last” in the sense of that website being online and working for a long time. I’d say certainly yes. HTML and CSS were around before I got here, are actively developed, and no other technologies are even trying to unseat them. The closest threats are native platforms, but those are so fractured, closed, and lack the worldwide utility of the URL, that it doesn’t seem likely any native platform will unseat the web. It’s more likely (and we see this happening, even if it’s slow and fraught) that native platforms embrace the web instead.

Will an HTML and CSS website be perfectly functional in, say, 2041? I’d say certainly. I’ll bet ya a dollar.

Steren doesn’t mean that HTML and CSS is just the output, but there is also no tooling at all. No build process. No templating. Here’s what he says about updating something common like navigation across pages:

So… if I don’t use any templating system, how do I update my header, footer or nav? Well, simply by using the “Replace in files” feature of any good text editor. They don’t need frequent updates anyway. The benefits of using a templating system is not worth the cost of introducing the tooling it requires.

I admit this is drawing the line further back than I would. This feels just like trading one kind of technical debt for another. Now you’ll need to write scripts or an elaborate find-and-replace RegEx to do what you want to do, rather than reach for some form of HTML include, which there are a ton of ways to handle lightly.

But I get it. Especially since once you do add that one templating language (or whatever), the temptation is strong to keep adding to the system, introducing more and more liabilities with less consideration on how they may be “limiting the lifespan” of the project.

I don’t actually think the stack matters that much.

In thinking about sites I work on (and have worked on), the longevity of the site doesn’t feel particularly related to the stack. Like, at all. The sites with the longest lifespans (like this one) have long lifespans because I care about them, and they have all sorts of moving parts in the stack.

I pick technology to help with what I want to do. If my needs change, I change the technology. I don’t just say, ooops, my stack is off, I guess I’ll shut down the website forever.

If we’re talking about website longevity, I think the breakdown of how much things matter is more like this:

  • 80% How much I care about the website
  • 10% The website isn’t a financial burden
  • 5% The website isn’t a mental burden (“the stack” being some small part of this)
  • 5% I have access to the registrant and didn’t forget to renew the domain name before a squatter nabbed it


Tech Stacks and Website Longevity originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/tech-stacks-and-website-longevity/feed/ 8 333020
CUBE CSS https://css-tricks.com/cube-css/ https://css-tricks.com/cube-css/#respond Thu, 11 Jun 2020 20:59:06 +0000 https://css-tricks.com/?p=312696 A CSS methodology from Andy Bell:

The most important part of this methodology is the language itself: CSS. It’s key to note its existence in the name because some alternative approaches, such as BEM—which I have enjoyed for many


CUBE CSS originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
A CSS methodology from Andy Bell:

The most important part of this methodology is the language itself: CSS. It’s key to note its existence in the name because some alternative approaches, such as BEM—which I have enjoyed for many years—can veer very far away from Cascading Style Sheets. I love CSS, though and think that its core capabilities are actually key to scalable CSS.

A favorite bit…

[…] a design system doesn’t just make you think at a micro-level, but also at a macro-level, because you have to make not just decisions about pixels, but also high-level organisation decisions which the design system helps to solve. Design system work is actually diplomacy work, a lot of the time.

This is often where I see narrow, component-only tunnel vision fall short and really, these approaches are less design systems, but more component libraries that solve a much narrower cohort of problems.

I like the idea of approaching CSS both from an inside-out philosophy — focusing on styling very small specific things then grouping them together to grow bigger thing — and from an outside-in philosophy — not forgetting that components need to be composed together sensibly.

To Shared LinkPermalink on CSS-Tricks


CUBE CSS originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/cube-css/feed/ 0 312696
Building a Scalable CSS Architecture With BEM and Utility Classes https://css-tricks.com/building-a-scalable-css-architecture-with-bem-and-utility-classes/ https://css-tricks.com/building-a-scalable-css-architecture-with-bem-and-utility-classes/#comments Tue, 21 Apr 2020 14:43:29 +0000 https://css-tricks.com/?p=306134 Maintaining a large-scale CSS project is hard. Over the years, we’ve witnessed different approaches aimed at easing the process of writing scalable CSS. In the end, we all try to meet the following two goals:

  1. Efficiency: we want to


Building a Scalable CSS Architecture With BEM and Utility Classes originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
Maintaining a large-scale CSS project is hard. Over the years, we’ve witnessed different approaches aimed at easing the process of writing scalable CSS. In the end, we all try to meet the following two goals:

  1. Efficiency: we want to reduce the time spent thinking about how things should be done and increase the time doing things.
  2. Consistency: we want to make sure all developers are on the same page.

For the past year and a half, I’ve been working on a component library and a front-end framework called CodyFrame. We currently have 220+ components. These components are not isolated modules: they’re reusable patterns, often merged into each other to create complex templates.

The challenges of this project have forced our team to develop a way of building scalable CSS architectures. This method relies on CSS globals, BEM, and utility classes.

I’m happy to share it! 👇

CSS Globals in 30 seconds

Globals are CSS files containing rules that apply crosswise to all components (e.g., spacing scale, typography scale, colors, etc.). Globals use tokens to keep the design consistent across all components and reduce the size of their CSS.

Here’s an example of typography global rules:

/* Typography | Global */
:root {
  /* body font size */
  --text-base-size: 1em;


  /* type scale */
  --text-scale-ratio: 1.2;
  --text-xs: calc((--text-base-size / var(--text-scale-ratio)) / var(--text-scale-ratio));
  --text-sm: calc(var(--text-xs) * var(--text-scale-ratio));
  --text-md: calc(var(--text-sm) * var(--text-scale-ratio) * var(--text-scale-ratio));
  --text-lg: calc(var(--text-md) * var(--text-scale-ratio));
  --text-xl: calc(var(--text-lg) * var(--text-scale-ratio));
  --text-xxl: calc(var(--text-xl) * var(--text-scale-ratio));
}


@media (min-width: 64rem) { /* responsive decision applied to all text elements */
  :root {
    --text-base-size: 1.25em;
    --text-scale-ratio: 1.25;
  }
}


h1, .text-xxl   { font-size: var(--text-xxl, 2.074em); }
h2, .text-xl    { font-size: var(--text-xl, 1.728em); }
h3, .text-lg    { font-size: var(--text-lg, 1.44em); }
h4, .text-md    { font-size: var(--text-md, 1.2em); }
.text-base      { font-size: --text-base-size; }
small, .text-sm { font-size: var(--text-sm, 0.833em); }
.text-xs        { font-size: var(--text-xs, 0.694em); }

BEM in 30 seconds

BEM (Blocks, Elements, Modifiers) is a naming methodology aimed at creating reusable components.

Here’s an example:

<header class="header">
  <a href="#0" class="header__logo"><!-- ... --></a>
  <nav class="header__nav">
    <ul>
      <li><a href="#0" class="header__link header__link--active">Homepage</a></li>
      <li><a href="#0" class="header__link">About</a></li>
      <li><a href="#0" class="header__link">Contact</a></li>
    </ul>
  </nav>
</header>
  • A block is a reusable component
  • An element is a child of the block (e.g., .block__element)
  • A modifier is a variation of a block/element (e.g., .block--modifier, .block__element--modifier).

Utility classes in 30 seconds

A utility class is a CSS class meant to do only one thing. For example:

<section class="padding-md">
  <h1>Title</h1>
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
</section>


<style>
  .padding-sm { padding: 0.75em; }
  .padding-md { padding: 1.25em; }
  .padding-lg { padding: 2em; }
</style>

You can potentially build entire components out of utility classes:

<article class="padding-md bg radius-md shadow-md">
  <h1 class="text-lg color-contrast-higher">Title</h1>
  <p class="text-sm color-contrast-medium">Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
</article>

You can connect utility classes to CSS globals:

/* Spacing | Global */
:root {
  --space-unit: 1em;
  --space-xs:   calc(0.5 * var(--space-unit));
  --space-sm:   calc(0.75 * var(--space-unit));
  --space-md:   calc(1.25 * var(--space-unit));
  --space-lg:   calc(2 * var(--space-unit));
  --space-xl:   calc(3.25 * var(--space-unit));
}

/* responsive rule affecting all spacing variables */
@media (min-width: 64rem) {
  :root {
    --space-unit:  1.25em; /* 👇 this responsive decision affects all margins and paddings */
  }
}

/* margin and padding util classes - apply spacing variables */
.margin-xs { margin: var(--space-xs); }
.margin-sm { margin: var(--space-sm); }
.margin-md { margin: var(--space-md); }
.margin-lg { margin: var(--space-lg); }
.margin-xl { margin: var(--space-xl); }

.padding-xs { padding: var(--space-xs); }
.padding-sm { padding: var(--space-sm); }
.padding-md { padding: var(--space-md); }
.padding-lg { padding: var(--space-lg); }
.padding-xl { padding: var(--space-xl); }

A real-life example

Explaining a methodology using basic examples doesn’t bring up the real issues nor the advantages of the method itself.

Let’s build something together! 

We’ll create a gallery of card elements. First, we’ll do it using only the BEM approach, and we’ll point out the issues you may face by going BEM only. Next, we’ll see how Globals reduce the size of your CSS. Finally, we’ll make the component customizable introducing utility classes to the mix.

Here’s a look at the final result:

Let’s start this experiment by creating the gallery using only BEM:

<div class="grid">
  <article class="card">
    <a class="card__link" href="#0">
      <figure>
        <img class="card__img" src="/image.jpg" alt="Image description">
      </figure>


      <div class="card__content">
        <h1 class="card__title-wrapper"><span class="card__title">Title of the card</span></h1>


        <p class="card__description">Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempore, totam?</p>
      </div>


      <div class="card__icon-wrapper" aria-hidden="true">
        <svg class="card__icon" viewBox="0 0 24 24"><!-- icon --></svg>
      </div>
    </a>
  </article>


  <article class="card"><!-- card --></article>
  <article class="card"><!-- card --></article>
  <article class="card"><!-- card --></article>
</div>

In this example, we have two components: .grid and .card. The first one is used to create the gallery layout. The second one is the card component.

First of all, let me point out the main advantages of using BEM: low specificity and scope.

/* without BEM */
.grid {}
.card {}
.card > a {}
.card img {}
.card-content {}
.card .title {}
.card .description {}


/* with BEM */
.grid {}
.card {}
.card__link {}
.card__img {}
.card__content {}
.card__title {}
.card__description {}

If you don’t use BEM (or a similar naming method), you end up creating inheritance relationships (.card > a).

/* without BEM */
.card > a.active {} /* high specificity */


/* without BEM, when things go really bad */
div.container main .card.is-featured > a.active {} /* good luck with that 😦 */


/* with BEM */
.card__link--active {} /* low specificity */

Dealing with inheritance and specificity in big projects is painful. That feeling when your CSS doesn’t seem to be working, and you find out it’s been overwritten by another class 😡! BEM, on the other hand, creates some kind of scope for your components and keeps specificity low.

But… there are two main downsides of using only BEM:

  1. Naming too many things is frustrating
  2. Minor customizations are not easy to do or maintain

In our example, to stylize the components, we’ve created the following classes:

.grid {}
.card {}
.card__link {}
.card__img {}
.card__content {}
.card__title-wrapper {}
.card__title {}
.card__description {}
.card__icon-wrapper {}
.card__icon {}

The number of classes is not the issue. The issue is coming up with so many meaningful names (and having all your teammates use the same naming criteria).

For example, imagine you have to modify the card component by including an additional, smaller paragraph:

<div class="card__content">
  <h1 class="card__title-wrapper"><span class="card__title">Title of the card</span></h1>
  <p class="card__description">Lorem ipsum dolor...</p>
  <p class="card__description card__description--small">Lorem ipsum dolor...</p> <!-- 👈 -->
</div>

How do you call it? You could consider it a variation of the .card__description element and go for .card__description .card__description--small. Or, you could create a new element, something like .card__small, .card__small-p, or .card__tag. See where I’m going? No one wants to spend time thinking about class names. BEM is great as long as you don’t have to name too many things.

The second issue is dealing with minor customizations. For example, imagine you have to create a variation of the card component where the text is center-aligned.

You’ll probably do something like this:

<div class="card__content card__content--center"> <!-- 👈 -->
  <h1 class="card__title-wrapper"><span class="card__title">Title of the card</span></h1>
  <p class="card__description">Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempore, totam?</p>
</div>


<style>
  .card__content--center { text-align: center; }
</style>

One of your teammates, working on another component (.banner), is facing the same problem. They create a variation for their component as well:

<div class="banner banner--text-center"></div>


<style>
  .banner--text-center { text-align: center; }
</style>

Now imagine you have to include the banner component into a page. You need the variation where the text is aligned in the center. Without checking the CSS of the banner component, you may instinctively write something like banner banner--center in your HTML, because you always use --center when you create variations where the text is center-aligned. Not working! Your only option is to open the CSS file of the banner component, inspect the code, and find out what class should be applied to align the text in the center.

How long would it take, 5 minutes? Multiply 5 minutes by all the times this happens in a day, to you and all your teammates, and you realize how much time is wasted. Plus, adding new classes that do the same thing contributes to bloating your CSS.

CSS Globals and utility classes to the rescue

The first advantage of setting global styles is having a set of CSS rules that apply to all the components.

For example, if we set responsive rules in the spacing and typography globals, these rules will affect the grid and card components as well. In CodyFrame, we increase the body font size at a specific breakpoint; because we use “em” units for all margins and paddings, the whole spacing system is updated at once generating a cascade effect.

Spacing and typography responsive rules — no media queries on a component level 

As a consequence, in most cases, you won’t need to use media queries to increase the font size or the values of margins and paddings!

/* without globals */
.card { padding: 1em; }


@media (min-width: 48rem) {
  .card { padding: 2em; }
  .card__content { font-size: 1.25em; }
}


/* with globals (responsive rules intrinsically applied) */
.card { padding: var(--space-md); }

Not just that! You can use the globals to store behavioral components that can be combined with all other components. For example, in CodyFrame, we define a .text-component class that is used as a “text wrapper.” It takes care of line height, vertical spacing, basic styling, and other things.

If we go back to our card example, the .card__content element could be replaced with the following:

<!-- without globals -->
<div class="card__content">
  <h1 class="card__title-wrapper"><span class="card__title">Title of the card</span></h1>
  <p class="card__description">Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempore, totam?</p>
</div>


<!-- with globals -->
<div class="text-component">
  <h1 class="text-lg"><span class="card__title">Title of the card</span></h1>
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempore, totam?</p>
</div>

The text component will take care of the text formatting, and make it consistent across all the text blocks in your project. Plus, we’ve already eliminated a couple of BEM classes.

Finally, let’s introduce the utility classes to the mix!

Utility classes are particularly useful if you want the ability to customize the component later on without having to check its CSS.

Here’s how the structure of the card component changes if we swap some BEM classes with utility classes:

<article class="card radius-lg">
  <a href="#0" class="block color-inherit text-decoration-none">
    <figure>
      <img class="block width-100%" src="image.jpg" alt="Image description">
    </figure>


    <div class="text-component padding-md">
      <h1 class="text-lg"><span class="card__title">Title of the card</span></h1>
      <p class="color-contrast-medium">Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempore, totam?</p>
    </div>


    <div class="card__icon-wrapper" aria-hidden="true">
      <svg class="icon icon--sm color-white" viewBox="0 0 24 24"><!-- icon --></svg>
    </div>
  </a>
</article>

The number of BEM (component) classes has shrunk from 9 to 3:

.card {}
.card__title {}
.card__icon-wrapper {}

That means you won’t deal much with naming things. That said, we can’t avoid the naming issue entirely: even if you create Vue/React/SomeOtherFramework components out of utility classes, you still have to name the components.

All the other BEM classes have been replaced by utility classes. What if you have to make a card variation with a bigger title? Replace text-lg with text-xl. What if you want to change the icon color? Replace color-white with color-primary. How about aligning the text in the center? Add text-center to the text-component element. Less time thinking, more time doing!

Why don’t we just use utility classes?

Utility classes speed-up the design process and make it easier to customize things. So why don’t we forget about BEM and use only utility classes? Two main reasons:

By using BEM together with utility classes, the HTML is easier to read and customize.

Use BEM for:

  • DRY-ing the HTML from the CSS you don’t plan on customizing (e.g., behavioral CSS-like transitions, positioning, hover/focus effects),
  • advanced animations/effects.

Use utility classes for:

  • the “frequently-customized” properties, often used to create component variations (like padding, margin, text-alignment, etc.),
  • elements that are hard to identify with a new, meaningful class name (e.g., you need a parent element with a position: relative → create <div class="position-relative"><div class="my-component"></div></div>).

Example: 

<!-- use only Utility classes -->
<article class="position-relative overflow-hidden bg radius-lg transition-all duration-300 hover:shadow-md col-6@sm col-4@md">
  <!-- card content -->
</article>


<!-- use BEM + Utility classes -->
<article class="card radius-lg col-6@sm col-4@md">
  <!-- card content -->
</article>

For these reasons, we suggest that you don’t add the !important rule to your utility classes. Using utility classes doesn’t need to be like using a hammer. Do you think it would be beneficial to access and modify a CSS property in the HTML? Use a utility class. Do you need a bunch of rules that won’t need editing? Write them in your CSS. This process doesn’t need to be perfect the first time you do it: you can tweak the component later on if required. It may sound laborious “having to decide” but it’s quite straightforward when you put it to practice.

Utility classes are not your best ally when it comes to creating unique effects/animations.

Think about working with pseudo-elements, or crafting unique motion effects that require custom bezier curves. For those, you still need to open your CSS file.

Consider, for example, the animated background effect of the card we’ve designed. How hard would it be to create such an effect using utility classes?

The same goes for the icon animation, which requires animation keyframes to work:

.card:hover .card__title {
  background-size: 100% 100%;
}


.card:hover .card__icon-wrapper .icon {
  animation: card-icon-animation .3s;
}


.card__title {
  background-image: linear-gradient(transparent 50%, alpha(var(--color-primary), 0.2) 50%);
  background-repeat: no-repeat;
  background-position: left center;
  background-size: 0% 100%;
  transition: background .3s;
}


.card__icon-wrapper {
  position: absolute;
  top: 0;
  right: 0;
  width: 3em;
  height: 3em;
  background-color: alpha(var(--color-black), 0.85);
  border-bottom-left-radius: var(--radius-lg);
  display: flex;
  justify-content: center;
  align-items: center;
}


@keyframes card-icon-animation {
  0%, 100% {
    opacity: 1;
    transform: translateX(0%);
  }
  50% {
    opacity: 0;
    transform: translateX(100%);
  }
  51% {
    opacity: 0;
    transform: translateX(-100%);
  }
}

Final result

Here’s the final version of the cards gallery. It also includes grid utility classes to customize the layout.

File structure

Here’s how the structure of a project built using the method described in this article would look like:

project/
└── main/
    ├── assets/
    │   ├── css/
    │   │   ├── components/
    │   │   │   ├── _card.scss
    │   │   │   ├── _footer.scss
    │   │   │   └── _header.scss
    │   │   ├── globals/
    │   │   │   ├── _accessibility.scss
    │   │   │   ├── _breakpoints.scss
    │   │   │   ├── _buttons.scss
    │   │   │   ├── _colors.scss
    │   │   │   ├── _forms.scss
    │   │   │   ├── _grid-layout.scss
    │   │   │   ├── _icons.scss
    │   │   │   ├── _reset.scss
    │   │   │   ├── _spacing.scss
    │   │   │   ├── _typography.scss
    │   │   │   ├── _util.scss
    │   │   │   ├── _visibility.scss
    │   │   │   └── _z-index.scss
    │   │   ├── _globals.scss
    │   │   ├── style.css
    │   │   └── style.scss
    │   └── js/
    │       ├── components/
    │       │   └── _header.js
    │       └── util.js
    └── index.html

You can store the CSS (or SCSS) of each component into a separate file (and, optionally, use PostCSS plugins to compile each new /component/componentName.css file into style.css). Feel free to organize the globals as you prefer; you could also create a single globals.css file and avoid separating the globals in different files.

Conclusion

Working on large-scale projects requires a solid architecture if you want to open your files months later and don’t get lost. There are many methods out there that tackle this issue (CSS-in-JS, utility-first, atomic design, etc.).

The method I’ve shared with you today relies on creating crosswise rules (globals), using utility classes for rapid development, and BEM for modular (behavioral) classes.

You can learn in more detail about this method on CodyHouse. Any feedback is welcome!


Building a Scalable CSS Architecture With BEM and Utility Classes originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/building-a-scalable-css-architecture-with-bem-and-utility-classes/feed/ 13 306134
Considerations for Creating a Card Component https://css-tricks.com/considerations-for-creating-a-card-component/ https://css-tricks.com/considerations-for-creating-a-card-component/#comments Mon, 02 Mar 2020 20:04:40 +0000 https://css-tricks.com/?p=303926 Even a simple Card component can be tricky to design an API around. What abstraction are you providing? How much control do you want to give? If you make it too flexible, you aren't providing much value. If you make it to rigid, you also aren't providing much value.


Considerations for Creating a Card Component originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
Here’s a Card component in React:

const Card = props => {
  return(
    <div className="card">
      <h2>{props.title}</h2>
      <p>{props.content}</p>
    </div>
  )
}

It might be pretty useful! If you end up using this thing hundreds of times, now you have the ability to refactor a little bit of HTML across your app very easily. You already have that power in CSS because of the class name there, but now you have HTML control too. Feel it.

But wait. Maybe this is limiting… an <h2>? What if that really should have been an <h4> in some usages? What’s the approach there? Maybe an API of sorts?

const Card = props => {
  return(
    <div className="card">
      {props.type === "big" && <h2>{props.title}</h2>}
      {props.type !== "big" && <h4>{props.title}</h4>}
      <p>{props.content}</p>
    </div>
  )
}

Or maybe we force a level to be passed in?

const Card = props => {
  const HeaderTag = `h${props.level}`;
  return(
    <div className="card">
      <HeaderTag>{props.title}</HeaderTag>
      <p>{props.content}</p>
    </div>
  )
}

Or maybe that header is its own component?

And a forced paragraph tag wrapper around that content? That’s a little limiting, isn’t it? Maybe that should be a <div> so that it could take arbitrary HTML inside it, like multiple paragraphs.

const Card = props => {
  return(
    <div className="card">
      <WhateverHeader>{props.title}</WhateverHeader>
      <div>{props.content}</div>
    </div>
  )
}

Actually, why even ask for content with props? It’s probably easier to deal with a child component, especially if what is coming over is HTML.

const Card = props => {
  return(
    <div className="card">
      <WhateverHeader>{props.title}</WhateverHeader>
      {children}
    </div>
  )
}

There are more assumptions we could challenge too. Like card only for a class name… shouldn’t that be more flexible?

const Card = props => {
  const classes = `card ${props.className}`;
  return(
    <div className={classes}>
      <WhateverHeader>{props.title}</WhateverHeader>
      {children}
    </div>
  )
}

I’m still forcing card there. We could drop that so that it isn’t assumed, or build another aspect of the Card API providing a way to opt-out of it.

Even the <div> wrapper is presumptuous. Perhaps that tag name could be passed in so that you could make it into a <section> or <article> or whatever you want.

Maybe it’s better to assume nothing actually, making our card like this:

const Card = () => {
  return(
    <>
      {children}
    </>
  )
}

That way anything you want to change, you have the freedom to change. At least then it’s flexibility while being relaxed about it, rather than this kind of “flexibility”:

<Card
  parentTag="article"
  headerLevel="3"
  headerTitle="My Card"
  contentWrapper="div"
  cardVariation="extra-large"
  contentContent=""
  this=""
  little=""
  piggy=""
  went=""
  to=""
  market=""
/>

That kind of extreme-API-zying just happens sometimes when you’re grasping for control and flexibility at the same time.

A component model with no guidance can lead to over-componentization also, like perhaps:

const Card = props => {
  return(
    <CardWrapperTheme>
      <CardWrapper>
        <CardTitle />
        <CardContent />
        <CardFooter />
      </CardWrapper>
    </CardWrapperTheme>
  )
}

There might be perfectly good reasons to do that, or it might be the result of componentizing because it’s “free” and just feels like that’s how things are done in an architecture that supports it.

There is a balance. If a component is too strict, it runs the risk of that people won’t use them because they don’t give them what they need. And if they’re too loose, people might not use them because they don’t provide any value, and, even if they did use them, they don’t offer any cohesiveness.

I don’t have any answers here, I just find it fascinating.


Considerations for Creating a Card Component originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/considerations-for-creating-a-card-component/feed/ 6 303926
This Page is Designed to Last https://css-tricks.com/this-page-is-designed-to-last/ https://css-tricks.com/this-page-is-designed-to-last/#comments Thu, 23 Jan 2020 16:02:08 +0000 https://css-tricks.com/?p=302005 Jeff Huang, while going through his collection of bookmarks, sadly finds a lot of old pages gone from the internet. Bit rot. It’s pretty bad. Most of what gets published on the web disappears. Thankfully, the Internet Archive gets a …


This Page is Designed to Last originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
Jeff Huang, while going through his collection of bookmarks, sadly finds a lot of old pages gone from the internet. Bit rot. It’s pretty bad. Most of what gets published on the web disappears. Thankfully, the Internet Archive gets a lot of it. Jeff has seven things that he thinks will help make a page last.

1) Return to vanilla HTML/CSS
2) Don’t minimize that HTML
3) Prefer one page over several
4) End all forms of hotlinking
5) Stick with the 13 web safe fonts +2
6) Obsessively compress your images
7) Eliminate the broken URL risk

I don’t take issue with any of that advice in general, but to me, they don’t all feel like things that have much to do with whether a site will last or not. Of them, #4 seems like the biggest deal, and #5 is… strange. (Fonts fall back on the web; what fonts you use should have no bearing on a site’s ability to last.)

I sort of agree with #1 and #2, but not on the surface. Both of them imply a build process. Build processes get old, they stop working, and they become a brick of technical debt. I still love them and can’t imagine day-to-day work without them, but they are things that stands in the way of people wanting to deal with an old site. Highly relevant: Simplicity, from Bastian Allgeier.

Everything listed is technological. If we’re talking technological advice to keeping a site online for the long haul, I’d say jamstack is the obvious answer. Prerender everything into static files. Rely on no third-party stuff anything, except a host. (Disclosure: Netlify is a current sponsor of this site, but I’m tellin’ ya, toss a simple static site without a complex build process up on Netlify, which has a generous free tier, and that site will absolutely be there for the long haul. )

Don’t diddle with your URLs either. Gosh darn it if I don’t see a lot of 404s because someone up and changed up all their URLs.

But I feel there is something beyond the technological that is the real trick to a site that lasts: you need to have some stake in the game. You don’t let your URLs die because you don’t want them to. They matter to you. You’ll tend to them if you have to. They benefit you in some way, so you’re incentivized to keep them around. That’s what makes a page last.

To Shared LinkPermalink on CSS-Tricks


This Page is Designed to Last originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/this-page-is-designed-to-last/feed/ 3 302005
Domain-Driven Design With React https://css-tricks.com/domain-driven-design-with-react/ https://css-tricks.com/domain-driven-design-with-react/#comments Mon, 16 Dec 2019 15:16:33 +0000 https://css-tricks.com/?p=299913 There is very little guidance on how to organize front-end applications in the world of React. (Just move files around until it “feels right,” lol). The truth is that we can do better. Let’s take a look at one pattern …


Domain-Driven Design With React originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
There is very little guidance on how to organize front-end applications in the world of React. (Just move files around until it “feels right,” lol). The truth is that we can do better. Let’s take a look at one pattern you might consider using to architect your site.

At first, you might split up your code between /components and /containers folders. This works for small sites but you’ll find yourself look for something more robust when scaling to larger sites. Luckily, decades of research into systems design has given us a wealth of patterns to explore to create a scalable architecture.

One of those is domain-driven design, and it has regained popularity over the last few years. Let’s explore how we can use it in React-land.

A primer on domain-driven design

Domain-driven design (DDD) is the practice of managing complexity of software applications by relating their underlying data models to domain logic. That’s a mouthful, so let’s break it down further.

The domain is an ontology, meaning how things are grouped in the world. For example, the word joist has a very specific connection to the domain of building construction. Another word, like Mike, can belong to multiple domains, such as the domain of Biblical names (short for Michael), or in the domain of politics as it relates to the NATO phonetic alphabet.

When the design is domain-driven, it means we place the model of our domain (e.g. a playing card in the domain of Poker) in a context (e.g. the contextual grouping, such as a Game) to help manage the complexity.

Organizing a DDD site

Domain-driven design is specifically for handling the complexity of growing sites as they add more and more models. It doesn’t really make sense for a site with one model. Once you get to about four models, that’s a good time to start looking at binding your models to multiple contexts. This isn’t a hard-and-fast rule, so don’t feel like you have to break out into multiple contexts, but once you get above four models, those contextual groupings will begin to surface.

Start by organizing your domains

Let’s use Twitter as our example site to organize. One way to separate domains within Twitter is to split up our models between the Blog platform that powers the Tweets and the Interaction elements that enable the micro-blogging to spread and flourish.

Is this the only way to separate concerns in Twitter? Definitely not! One key aspect of DDD is that there is no one correct way to create domains. There are plenty of ways to split up the bounded contexts of an application, so don’t focus too much on the architecture we’ve chosen. Instead, use this as a springboard to understand how we can apply DDD to the organization of our front-end code.

That said, our code will now be structured to look like this (assuming you start with something like create-react-app):

twitter/
├── App.css
├── App.js
├── App.test.js
├── blog/
└── interaction/

Define the components and containers in each domain

Now that we have our basic folder structure set up, it is time to add some real components! Looking at our domain UML diagram above, it would be useful to start with containers that fetch data on a given page and components that organize the templates that compose those pages. Expanding on our app, we now have the following structure in place (omitting our accompanying test.js files for simplicity):

twitter/
├── App.css
├── App.js
├── App.test.js
├── blog/
│   ├── HomePage.js
│   ├── TweetCard.js
│   ├── TweetDialog.js
│   ├── TweetList.js
│   ├── TweetListItem.js
│   ├── UserPage.js
│   └── UserCard.js
└── interaction/
    ├── FollowButton.js
    ├── LikeButton.js
    └── ShareButton.js

We still keep our App file to initialize React to our root-level HTML tag. With our domains in place, we begin to build our containers (such as HomePage and UserPage) and components (such as TweetCard and TweetListItem). Alternatively, we could further segment the models within our domains to look like so:

twitter/
└── blog/
    ├── user/
    │   ├── HomePage.js
    │   ├── UserCard.js
    │   └── UserPage.js
    └── tweet/
        ├── TweetCard.js
        ├── TweetDialog.js
        ├── TweetList.js
        └── TweetListItem.js

But given the size of the application it isn’t necessary at this stage.

Add helpers, if they’re needed

As we build out our application our UIs will continue to increase in complexity. To deal with this, we have two methods for separating concerns and pulling logic out of our component templates: presenters and utilities. Presenters push all of the visual presentation logic out of the templates to keep the view layer as clean and simple as possible. Utilities collect shared functionality for all other logic on the front end that is not specifically related to the templates. Let’s examine these a bit closer.

Clean up templates with presenters

Think of a Twitter profile. What kinds of elements do you see here on my account?

There’s information directly related to my user: name, handle, description, location, website, birthday, start date. There are also counts of associations between other models — how many other users are following me? How many other users am I following? There’s additional logic that isn’t even captured on the page, such as my tweets, replies, media uploads, and content I’ve liked. To capture all of this presentational logic appropriately, we can add an additional file within our file tree to isolate our presenter pattern from the JSX component:

twitter/
└── blog/
    ├── user/
    │   ├── UserCard.js
    │   ├── UserCard.presenter.js

Push out logic into utilities

Certain presentational logic is so fundamental that it could be useful across applications regardless of whether or not it is used within rendering. Currency formatting, validations, and timestamp formatting are all use cases where we could benefit from isolated utility functions across our application. Where do those live? Since they span domains, utilities can be in their own folder:

    twitter/
    ├── App.css
    ├── App.js
    ├── App.test.js
    ├── blog/
    │   ├── HomePage.js
    │   ├── TweetCard.js
    │   ├── TweetDialog.js
    │   ├── TweetList.js
    │   ├── TweetListItem.js
    │   ├── UserCard.js
    │   ├── UserCard.presenterjs
    │   └── UserPage.js
    ├── interaction/
    │   ├── FollowButton.js
    │   ├── LikeButton.js
    │   └── ShareButton.js
    └── utils/
         ├── currency.js
         ├── time.js
         └── validation.js

There is no wrong way to organize your app!

Ultimately, the choice is yours. This is just one example for myriad ways you could arrange your application. Domain-driven design is a valuable tool because it separates business logic in a meaningful way, creates a clearer distinction for domain expertise amongst developers, and provides rules for easily organizing and scaling your code.

But if you’re looking for an alternative to the traditional chaos of React application file structures, take a look at domain-driven design. It may be just the thing.

Lastly, if you like this sort of content and want to learn more about front-end, user interface development, and UX design and research (organized by your experience in the industry), I run a free newsletter that you might want to check out.


Domain-Driven Design With React originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/domain-driven-design-with-react/feed/ 4 299913
CSS Architecture for Modern JavaScript Applications https://css-tricks.com/css-architecture-for-modern-javascript-applications/ Fri, 06 Dec 2019 15:15:34 +0000 https://css-tricks.com/?p=299777 There is a lot to like from Mike Riethmuller here:

  • The title. When you’re building a website from JavaScript-powered components anyway, that is a moment to talk about how to do styling, because it opens some doors to JavaScript-powered styles


CSS Architecture for Modern JavaScript Applications originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
There is a lot to like from Mike Riethmuller here:

  • The title. When you’re building a website from JavaScript-powered components anyway, that is a moment to talk about how to do styling, because it opens some doors to JavaScript-powered styles that you probably wouldn’t otherwise choose.
  • The personal experience and pragmatism. Drawing on five years of consulting, he’s seeing that component re-use and style understandability is suffering, not improving, partly due to every team having different approaches. He says “it’s a little bit of everybody’s fault” and sees the perspective of others who like parts of what JavaScript-powered styles can bring, like less dependence on specificity.
  • The fresh thinking. Since JavaScript-powered websites are all built by nested components anyway, why not use that architecture for styling? The thesis of the article is really about building UI components that, on purpose, don’t involve application logic but exist just for styling, and using a combination of clever CSS and JavaScript power to the kind of styling you need.

To Shared LinkPermalink on CSS-Tricks


CSS Architecture for Modern JavaScript Applications originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
299777
The Many Ways to Include CSS in JavaScript Applications https://css-tricks.com/the-many-ways-to-include-css-in-javascript-applications/ https://css-tricks.com/the-many-ways-to-include-css-in-javascript-applications/#comments Mon, 08 Jul 2019 20:45:52 +0000 http://css-tricks.com/?p=292197 Welcome to an incredibly controversial topic in the land of front-end development! I’m sure that a majority of you reading this have encountered your fair share of #hotdrama surrounding how CSS should be handled within a JavaScript application.

I …


The Many Ways to Include CSS in JavaScript Applications originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
Welcome to an incredibly controversial topic in the land of front-end development! I’m sure that a majority of you reading this have encountered your fair share of #hotdrama surrounding how CSS should be handled within a JavaScript application.

I want to preface this post with a disclaimer: There is no hard and fast rule that establishes one method of handling CSS in a React, or Vue, or Angular application as superior. Every project is different, and every method has its merits! That may seem ambiguous, but what I do know is that the development community we exist in is full of people who are continuously seeking new information, and looking to push the web forward in meaningful ways.

Preconceived notions about this topic aside, let’s take a look at the fascinating world of CSS architecture!

Let us count the ways

Simply Googling “How to add CSS to [insert framework here]” yields a flurry of strongly held beliefs and opinions about how styles should be applied to a project. To try to help cut through some of the noise, let’s examine a few of the more commonly utilized methods at a high level, along with their purpose.

Option 1: A dang ol’ stylesheet

We’ll start off with what is a familiar approach: a dang ol’ stylesheet. We absolutely are able to <link> to an external stylesheet within our application and call it a day.

<link rel="stylesheet" href="styles.css">

We can write normal CSS that we’re used to and move on with our lives. Nothing wrong with that at all, but as an application gets larger, and more complex, it becomes harder and harder to maintain a single stylesheet. Parsing thousands of lines of CSS that are responsible for styling your entire application becomes a pain for any developer working on the project. The cascade is also a beautiful thing, but it also becomes tough to manage in the sense that some styles you — or other devs on the project — write will introduce regressions into other parts of the application. We’ve experienced these issues before, and things like Sass (and PostCSS more recently) have been introduced to help us handle these issues

We could continue down this path and utilize the awesome power of PostCSS to write very modular CSS partials that are strung together via @import rules. This requires a little bit of work within a webpack config to be properly set up, but something you can handle for sure!

No matter what compiler you decide to use (or not use) at the end of the day, you’ll be serving one CSS file that houses all of the styles for your application via a <link> tag in the header. Depending on the complexity of that application, this file has the potential to get pretty bloated, hard to load asynchronously, and render-blocking for the rest of your application. (Sure, render-blocking isn’t always a bad thing, but for all intents and purposes, we’ll generalize a bit here and avoid render blocking scripts and styles wherever we can.)

That’s not to say that this method doesn’t have its merits. For a small application, or an application built by a team with less of a focus on the front end, a single stylesheet may be a good call. It provides clear separation between business logic and application styles, and because it’s not generated by our application, is fully within our control to ensure exactly what we write is exactly what is output. Additionally, a single CSS file is fairly easy for the browser to cache, so that returning users don’t have to re-download the entire file on their next visit.

But let’s say that we’re looking for a bit more of a robust CSS architecture that allows us to leverage the power of tooling. Something to help us manage an application that requires a bit more of a nuanced approach. Enter CSS Modules.

Option 2: CSS Modules

One fairly large problem within a single stylesheet is the risk of regression. Writing CSS that utilizes a fairly non-specific selector could end up altering another component in a completely different area of your application. This is where an approach called “scoped styles” comes in handy.

Scoped styles allow us to programmatically generate class names specific to a component. Thus scoping those styles to that specific component, ensuring that their class names will be unique. This leads to auto-generated class names like header__2lexd. The bit at the end is a hashed selector that is unique, so even if you had another component named header, you could apply a header class to it, and our scoped styles would generate a new hashed suffix like so: header__15qy_.

CSS Modules offer ways, depending on implementation, to control the generated class name, but I’ll leave that up to the CSS Modules documentation to cover that.

Once all is said and done, we are still generating a single CSS file that is delivered to the browser via a <link> tag in the header. This comes with the same potential drawbacks (render blocking, file size bloat, etc.) and some of the benefits (caching, mostly) that we covered above. But this method, because of its purpose of scoping styles, comes with another caveat: the removal of the global scope — at least initially.

Imagine you want to employ the use of a .screen-reader-text global class that can be applied to any component within your application. If using CSS Modules, you’d have to reach for the :global pseudo selector that explicitly defines the CSS within it as something that is allowed to be globally accessed by other components in the app. As long as you import the stylesheet that includes your :global declaration block into your component’s stylesheet, you’ll have the use of that global selector. Not a huge drawback, but something that takes getting used to.

Here’s an example of the :global pseudo selector in action:

// typography.css
:global {
  .aligncenter {
    text-align: center;
  }
  .alignright {
    text-align: right;
  }
  .alignleft {
    text-align: left;
  }
}

You may run the risk of dropping a whole bunch of global selectors for typography, forms, and just general elements that most sites have into one single :global selector. Luckily, through the magic of things like PostCSS Nested or Sass, you can import partials directly into the selector to make things a bit more clean:

// main.scss
:global {
  @import "typography";
  @import "forms";
}

This way, you can write your partials without the :global selector, and just import them directly into your main stylesheet.

Another bit that takes some getting used to is how class names are referenced within DOM nodes. I’ll let the individual docs for Vue, React, and Angular speak for themselves there. I’ll also leave you with a little example of what those class references look like utilized within a React component:

// ./css/Button.css

.btn {
  background-color: blanchedalmond;
  font-size: 1.4rem;
  padding: 1rem 2rem;
  text-transform: uppercase;
  transition: background-color ease 300ms, border-color ease 300ms;

  &:hover {
    background-color: #000;
    color: #fff;
  }
}

// ./Button.js

import styles from "./css/Button.css";

const Button = () => (
  <button className={styles.btn}>
    Click me!
  </button>
);

export default Button;

The CSS Modules method, again, has some great use cases. For applications looking to take advantage of scoped styles while maintaining the performance benefits of a static, but compiled stylesheet, then CSS Modules may be the right fit for you!

It’s worth noting here as well that CSS Modules can be combined with your favorite flavor of CSS preprocessing. Sass, Less, PostCSS, etc. are all able to be integrated into the build process utilizing CSS Modules.

But let’s say your application could benefit from being included within your JavaScript. Perhaps gaining access to the various states of your components, and reacting based off of the changing state, would be beneficial as well. Let’s say you want to easily incorporate critical CSS into your application as well! Enter CSS-in-JS.

Option 3: CSS-in-JS

CSS-in-JS is a fairly broad topic. There are several packages that work to make writing CSS-in-JS as painless as possible. Frameworks like JSS, Emotion, and Styled Components are just a few of the many packages that comprise this topic.

As a broad strokes explanation for most of these frameworks, CSS-in-JS is largely operates the same way. You write CSS associated with your individual component and your build process compiles the application. When this happens, most CSS-in-JS frameworks will output the associated CSS of only the components that are rendered on the page at any given time. CSS-in-JS frameworks do this by outputting that CSS within a <style> tag in the <head> of your application. This gives you a critical CSS loading strategy out of the box! Additionally, much like CSS Modules, the styles are scoped, and the class names are hashed.

As you navigate around your application, the components that are unmounted will have their styles removed from the <head> and your incoming components that are mounted will have their styles appended in their place. This provides opportunity for performance benefits on your application. It removes an HTTP request, it is not render blocking, and it ensures that your users are only downloading what they need to view the page at any given time.

Another interesting opportunity CSS-in-JS provides is the ability to reference various component states and functions in order to render different CSS. This could be as simple as replicating a class toggle based on some state change, or be as complex as something like theming.

Because CSS-in-JS is a fairly #hotdrama topic, I realized that there are a lot of different ways that folks are trying to go about this. Now, I share the feelings of many other people who hold CSS in high regard, especially when it comes to leveraging JavaScript to write CSS. My initial reactions to this approach were fairly negative. I did not like the idea of cross-contaminating the two. But I wanted to keep an open mind. Let’s look at some of the features that we as front-end-focused developers would need in order to even consider this approach.

  • If we’re writing CSS-in-JS we have to write real CSS. Several packages offer ways to write template-literal CSS, but require you to camel-case your properties — i.e. padding-left becomes paddingLeft. That’s not something I’m personally willing to sacrifice.
  • Some CSS-in-JS solutions require you to write your styles inline on the element you’re attempting to style. The syntax for that, especially within complex components, starts to get very hectic, and again is not something I’m willing to sacrifice.
  • The use of CSS-in-JS has to provide me with powerful tools that are otherwise super difficult to accomplish with CSS Modules or a dang ol’ stylesheet.
  • We have to be able to leverage forward-thinking CSS like nesting and variables. We also have to be able to incorporate things like Autoprefixer, and other add-ons to enhance the developer experience.

It’s a lot to ask of a framework, but for those of us who have spent most of our lives studying and implementing solutions around a language that we love, we have to make sure that we’re able to continue writing that same language as best we can.

Here’s a quick peek at what a React component using Styled Components could look like:

// ./Button.js
import styled from 'styled-components';

const StyledButton= styled.button`
  background-color: blanchedalmond;
  font-size: 1.4rem;
  padding: 1rem 2rem;
  text-transform: uppercase;
  transition: background-color ease 300ms, border-color ease 300ms;

  &:hover {
    background-color: #000;
    color: #fff;
  }
`;

const Button = () => (
  <StyledButton>
    Click Me!
  </StyledButton>
);

export default Button;

We also need to address the potential downsides of a CSS-in-JS solution — and definitely not as an attempt to spark more drama. With a method like this, it’s incredibly easy for us to fall into a trap that leads us to a bloated JavaScript file with potentially hundreds of lines of CSS — and that all comes before the developer will even see any of the component’s methods or its HTML structure. We can, however, look at this as an opportunity to very closely examine how and why we are building components the way they are. In thinking a bit more deeply about this, we can potentially use it to our advantage and write leaner code, with more reusable components.

Additionally, this method absolutely blurs the line between business logic and application styles. However, with a well-documented and well-thought architecture, other developers on the project can be eased into this idea without feeling overwhelmed.

TL;DR

There are several ways to handle the beast that is CSS architecture on any project and do so while using any framework. The fact that we, as developers, have so many choices is both super exciting, and incredibly overwhelming. However, the overarching theme that I think continues to get lost in super short social media conversations that we end up having, is that each solution has its own merits, and its own inefficiencies. It’s all about how we carefully and thoughtfully implement a system that makes our future selves, and/or other developers who may touch the code, thank us for taking the time to establish that structure.


The Many Ways to Include CSS in JavaScript Applications originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/the-many-ways-to-include-css-in-javascript-applications/feed/ 6 292197
The 10,000 Year Clock Design Principals https://css-tricks.com/the-10000-year-clock-design-principals/ Tue, 08 Jan 2019 14:55:12 +0000 http://css-tricks.com/?p=280948 In the new year edition of the Clearleft newsletter, Jeremy Keith linked to the design principals Danny Hillis thought about while considering a clock that would work for 10,000 years.

Here’s part of that page, satisfyingly displayed as a …


The 10,000 Year Clock Design Principals originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
In the new year edition of the Clearleft newsletter, Jeremy Keith linked to the design principals Danny Hillis thought about while considering a clock that would work for 10,000 years.

Here’s part of that page, satisfyingly displayed as a <dl>:

Longevity:
Go slow
Avoid sliding friction (gears)
Avoid ticking
Stay clean
Stay dry
Expect bad weather
Expect earthquakes
Expect non-malicious human interaction
Dont tempt thieves
Maintainability and transparency:
Use familiar materials
Allow inspection
Rehearse motions
Make it easy to build spare parts
Expect restarts
Include the manual
Scalability and Evolvabilty:
Make all parts similar size
Separate functions
Provide simple interfaces

How… good.

To Shared LinkPermalink on CSS-Tricks


The 10,000 Year Clock Design Principals originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
280948
8 simple rules for a robust, scalable CSS architecture https://css-tricks.com/8-simple-rules-robust-scalable-css-architecture/ Mon, 31 Oct 2016 23:35:15 +0000 http://css-tricks.com/?p=247257 I don’t disagree on any particular point on this thesis by Jarno Rantanen.

This is the first I’ve seen this particular naming convention, which seems fine to me, but I’d add that any well-considering naming convention works.

Also, there is …


8 simple rules for a robust, scalable CSS architecture originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
I don’t disagree on any particular point on this thesis by Jarno Rantanen.

This is the first I’ve seen this particular naming convention, which seems fine to me, but I’d add that any well-considering naming convention works.

Also, there is this:

Cascading styles will ruin your day, eventually.

A sentiment shared by many these days, and the likely culprit for all the peter-griffin-adjusting-the-blinds.gifs out there in the world. Again I don’t entirely disagree, but, there are styles I gotta imagine even hardened CSS module aficionados would allow to cascade. For instance: why wouldn’t I let the body copy font-family cascade?

To Shared LinkPermalink on CSS-Tricks


8 simple rules for a robust, scalable CSS architecture originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
247257