DEV Community

Discussion on: CSS Is Hard - How do you learn to use and write CSS properly?

Collapse
 
antjanus profile image
Antonin J. (they/them)

I think the problem with CSS is a little different than SQL or JS.

The CSS problem has more to do with how you grow your codebase and how to deal with encapsulation vs. reuse. What's essentially "global" and what's not. And then how global rules effect encapsulated CSS.

For example, most of the work I've done with CSS involved building a top-level framework to encompass majority of styling usecases.

I might build a button. But buttons are tricky. You're inheriting from global styles (for typography), then you might have a .button class base which sets some rules, and then you're dealing with individual buttons and their usecases. There's a mix and match of reuse vs redefine and every class definition inherits from a number of parent classes/elements that are only visible in HTML.

The further down you cascade, the more difficult it is to grow that codebase because any small change in a top-level definition can affect everything.

Here's my example:

body {
  font-size: 16px;
}

.button {
  display: inline-block;
  background-color: #333;
  color: #fff;
  padding: 5px 10px;
}

.button--large {
  padding: 10px 15px;
  font-size: 18px;
}

.button-primary {
  background-color: green;
  color: #000;
}

Now imagine that within a button, you want to display an icon with some special properties:

.button-icon {
  color: #000;
  background-color: #fff;
  font-size: 11px;
}

We're already getting to some weird places here. For example, the button-icon will scale improperly with button--large. If this button is placed in some header, the expected button might look different if the header specificity will override it.

And if you do fix those scaling problems, the second you change something (eg. the button--large definition), you'll face problems down the line having to fix those.