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've seen BEM mentioned often as a way to scale CSS. Do you have any experience with it?

I've briefly tried it before and found myself getting tangled in very long class names in complicated components.

One of the newer approaches that looks very promising is that "utility-first" approach. ie. lots of small utility classes that you compose in the HTML and then extract out into component-based classes. What do you think about that?

Collapse
 
horus_sky profile image
Cedric W

BEM is mostly about readability. If you are working within a group or with vendors that are familiar with the syntax, even seeing the code for the first time, they wouldn't have to do much to parse what classes are for what. BEM is just a naming convention, so you can still have a "utility-first" approach or atomic design to your CSS.

Overall, you can think of BEM as:
'.block__element — modifier' (hence the name)

For example:
5 Reasons To Use BEM
Based on the above image, I know at a glance:

  • This is a card component; with .card being the block
  • Everything with an "__" (underscore) are child elements that are dependent on the main .card class; title, text, btn, etc.
  • I also know that the second paragraph has a modifier signified by "--" (double dashes); meaning it inheriting styles but also changing them up; ideally you would want your modifiers below the main styles for "specificity" reasons -- this will cause them not to be overwritten.

5 Reasons To Use BEM

Now take the above card for example. The HTML is the same, however,

We have a modifier in the main block. This modifier causes it to be green. Notice the modifier style under the main block style...for the same reason aforementioned--specificity.

Naming

As far as BEM classes getting a bit long. This can happen, however, this can be more the developers issue and not exactly on the naming convention itself. Do we have to spell out the word "button" or can you shorten it to "btn"? Does it still get the idea across? Thats up to you and your team.

Again I highly recommend reading up on BEM. It may or maynot be for you. I found it a bit silly at first but forced myself and my team to use it because we had to collaborate with an off-shore team that uses BEM. After a few days, it became the norm. It doesn't take long to understand the concept, just takes more time getting use to double dashes and underscores.


credit:
5 Reasons To Use BEM (a.k.a. why is BEM G.R.E.A.T.)