0

I am trying to refactor this piece of CSS code using commas so I am not duplicating the same set of rules for every elements. Here I want specific children elements of .clear to be invisible when the class .clear. is toggled.

    .clear select {
        opacity: 0;
        transition: 0.2s;
    }

    .clear input {
        opacity: 0;
        transition: 0.2s;
    }

    .clear p {
        opacity: 0;
        transition: 0.2s;
    }

    .clear .section-content {
        opacity: 0;
        transition: 0.2s;
    }

This works, but doesn't look too efficient. From my understanding, commas are used to apply the same set of rules to multiple elements.

    .clear select,input,p,.section-content {
        opacity: 0;
        transition: 0.2s;
    }

Now if I refactor this way, no matter if .clear class is toggled or not in my HTML, all element will be invisible.

What would be the correct way to make this work in one set of rules ?

Philx94
  • 616
  • 3
  • 12
  • 30
  • 1
    You need to add the .clear class in front of every selectors, so only the classes within the .clear class is styled: .clear select, .clear input, .clear p, .clear .section-content – TheYaXxE Feb 08 '21 at 22:09
  • This seems like a rather strange choice for a duplicate question... This is a completely different question than the linked one. It does, however, seem to be similar to [this question](https://stackoverflow.com/questions/6192596/how-to-select-multiple-elements-that-are-children-of-given-element). – Jacob Lockard Feb 08 '21 at 23:07

2 Answers2

1

As stated here, you pretty much have to use .clear multiple times, like so:

.clear select, .clear input, .clear p, .clear .section-content {
  opacity: 0;
  transition: 0.2s;
}

Sadly, with CSS alone there is no other way.

Jacob Lockard
  • 1,026
  • 9
  • 21
1

In CSS, commas are used to define selector lists against a single style block. You would need to prepend every target element with the .clear selector to achieve what you want:

.clear select,
.clear input,
.clear p,
.clear .section-content {
    opacity: 0;
    transition: 0.2s;
}

If you're looking to level-up your stylesheets, you could consider using Sass instead to leverage nesting, meaning you could write it like this:

.clear {
  select,
  input,
  p,
  .section-content {
    opacity: 0;
    transition: 0.2s;
  }
}
codeth
  • 537
  • 3
  • 7
  • Interesting! I'm wondering why was this downvoted. This Sass syntax does look unfamiliar. I'll try it! – Philx94 Feb 08 '21 at 22:32