Search code examples
htmlcssoopoocss

Object oriented CSS


I watched this presentation about object oriented css, but I think I either don't understand it correctly or don't understand the benefits of using OO CSS:

Example HTML:

<div class="border-1 bg-2 color-1 font-1">
</div>

Example CSS:

/* borders */
.border-1 { border: 1px solid red; }

/* backgrounds: */
.bg-2 { background: yellow; }

/* other sections */

I see an advantage in being able to change styles for multiple elements quickly, for instance, being able to switch the color scheme would be very useful.

But actually, you're defining the style/look inside the HTML, or at least a part of it. Of course, it's better than using the style attribute, because you still are able to exchange the styles for a set of groups.

The point is, you are defining the style-groups inside the HTML, but I learned that you should create "logical" groups inside the HTML (e.g. class="nav-item" / class="btn submit-btn") and the CSS completely applies the style and defines which elements belong together from the "stylistic" point of view (e.g. .nav-item, .submit-btn { background: red; }).

Maybe I totally misunderstood the concept. However, I still don't know a good way of constructing my CSS.


Solution

  • CSS isn't object oriented. My suggestion is to forget what you've read about "object oriented CSS" and instead focus on the problems with CSS you're trying to solve. If they are to make CSS easier to write, read and maintain, or to get more features (like CSS variables) I think Less or Sass will suit your need much better.

    Using CSS like what's suggested with "object oriented CSS" just leads to terrible, non-semantic and meaningless CSS that in the long run isn't any easier to maintain than "ordinary" CSS. Both id and class should have semantic and meaningful names, so using a framework that allows you to write semantic CSS (that describes intent instead of presentation) is in my humble opinion much better.