Skip to main content

+only-for

Two use cases

There is a very helpful mixin the +only-for. It has two use cases:

  • with tree-structural pseudo-classes
  • as a reducer inside multiple mutation group

Tree-structural pseudo-classes

Tree-structural pseudo-classes are those pseudo-classes that are related to the location of an element within the document tree:

  • :first-child
  • :last-child
  • :first-of-type
  • :last-of-type
  • :nth-child(n)
  • :nth-last-child(n)
  • :nth-last-of-type(n)
  • :nth-of-type(n)
  • :only-of-type
  • :only-child
  • :empty

In most cases, it doesn't make sense for the pseudo-classes above to register as separate variants. It's not something that the frontend developer explicitly set to HTML. It is an implicit behavior.

Obs: But you can register it as a variant if you have a good reason.

So the solution is using it as an unregistered mutation with the +only-for:

+______________________________
+element('p')
+default
margin: 10px 0

+only-for(':first-child')
margin: 0


p {
margin: 10px 0;
}

p:first-child {
margin: 0;
}

Once again, there is no need to register tree-structural pseudo-classes. Just use them as a separate mutation in combination with the +only-for mixin.

Reducer for multiple mutations

The second way of using the mixin +only-for is to reduce the scope of the current block. It could be a group of mutations, elements, or even pseudo-elements.

This way is possible to write the shared CSS for the group and then the specific code with the +only-for mixin.

The mixin +only-for is used the same way as other mutations, so the +default mixin is required too.

Example of grouped mutations:

+register
+variant('.lorem')
+variant('.ipsum')

...

+variant('.lorem', '.ipsum')
+default
overflow: hidden
margin: 1em

+only-for('.lorem')
display: block

+only-for('.ipsum')
display: flex







.lorem, .ipsum {
overflow: hidden;
margin: 1em;
}

.lorem {
display: block;
}
.ipsum {
display: flex;
}


Example of exclusive mutations:

+register
+state('{collapsible}', '.expanded', '.collapsed')

...

+state('{collapsible}')
+default
overflow: hidden
margin: 1em

+only-for('.expanded')
display: block

+only-for('.collapsed')
display: flex






.expanded, .collapsed {
overflow: hidden;
margin: 1em;
}

.expanded {
display: block;
}
.collapsed {
display: flex;
}


Example of elements:

+____________________________________
+element('th', 'td')
+default
overflow: hidden
margin: 1em

+only-for('th')
color: white

+only-for('td')
color: grey


th, td {
overflow: hidden;
margin: 1em;
}

th {
color: white;
}
td {
color: grey;
}


Example of pseudo-elements:

+____________________________________
+pseudo-element('before', 'after')
+default
overflow: hidden
margin: 1em

+only-for('::before')
color: white

+only-for('::after')
color: grey


my-button::before, my-button::after {
overflow: hidden;
margin: 1em;
}

my-button::before {
color: white;
}
my-button::after {
color: grey;
}