Nested Component Styling Based On Parent

As we are building modular components there will inevitably come a time when relationships between components will become needed. Specifically changing the style of a child component when it is inside a parent component.

Traditionally we would be forced to write CSS code similar to this:

.Team {
  border: 1px solid #ccc;
}

.Person {
  background: #ccc;
  margin: 10px;
}

.Team .Person {
  margin: 5px;
}

Here we are reducing margin on the Person component when it is inside the Team component.

The problem comes as this scales and you start building hard relationships between components where a component’s style is actually dictated inside another component’s CSS files.

To solve this you can maintain each state of the component as modifiers and then use extending within a pre-processor. Let’s do this for the simple example above.

First let’s create a new Person state called Person--small.

.Person {
  background: #ccc;
  margin: 10px;
}

.Person--small {
  margin: 5px;
}

Then we need to trigger this modifier when it is inside the Team component. This example is using the reworkcss framework.

.Team .Person {
  extend: .Person--small;
}

Now we have loosely coupled the two components and have kept control of each state the Person component can be in within the Person CSS itself.

Work with me

Dave is a cohesive team member, widely popular with his colleagues and always inspiring quality, exploration and innovation. One of the true ‘greats’ we’ve had the pleasure to work with

I believe in community, in inspiration and creativity. I believe it's an inspired team and a laser focus on the user's experiece that will produce the best results. I want to help frontend teams live inspired, be productive and scale better.