My question is different than this one, but it's regarding the same principle, so this quote is relevant here too:

from https://github.com/stubbornella/oocss/wiki

Essentially, this means “rarely use location-dependent styles”. An object should look the same no matter where you put it. So instead of styling a specific h2 with .myObject h2 {...}, create and apply a class that describes the h2 in question, like h2 class="category".

But what if the design dictates that an object's style changes when it's inside certain containers? Here's a simplified example of my problem. Let's say there's an object called foo, and a container object called bar. foo and bar have their own location-independent styles:

.foo {
    ...
}
.bar {
    ...
}

But when foo is inside container bar like so, its color needs to change when the user hovers over bar:

<div class="bar">
    ...
    <div class="foo">
        ...
    </div>
    ...
</div>

It seems in this case, you can't avoid writing a location-dependent selector that looks like this:

.bar:hover .foo {
    // color style
}

One solution I thought of is to introduce a class that's explicitly dependent on bar (named using BEM naming convention to be explicit about parent-child relationship), and add it to the foo object:

<div class="bar">
    ...
    <div class="foo bar__foo">
        ...
    </div>
    ...
</div>

.bar:hover .bar__foo {
    // color style
}

I want to confirm, is this a good way to handle the issue? Are there other ways in OOCSS as well?

1

There are 1 best solutions below

0
On

The big concern here isn't that your chaining classes together, it's that your classes are location independent. Nesting is going to happen. Approaches like OOCSS are great because they help to you know when things like nesting and class-naming is going awry.

Mark Otto released a Code Guide last week and here are some relevant points:

  • Keep selectors short and strive to limit the number of elements in each selector to three.
  • Scope classes to the closest parent only when necessary (e.g., when not using prefixed classes).

He also provides these examples:

/* Bad example */
span { ... }
.page-container #stream .stream-item .tweet .tweet-header .username { ... }
.avatar { ... }

/* Good example */
.avatar { ... }
.tweet-header .username { ... }
.tweet .avatar { ... }

In short: Aim to scope a class to it's parent. Don't go further than 3 selectors.

You're fine going with:

.bar:hover .foo { ... } 

Further Reading