Adam Baranyai
Adam Baranyai

Reputation: 3867

Overwrite multi-classed css with single class css

I am using two separate CSS files with media queries to achieve different styles based on the screen size of the viewer. I have the following lines in my desktop css file:

Desktop CSS:

.labelContainer .labelText.labelText_xl {
  width: 155px;
}

.labelContainer .labelText.labelText_big {
  width: 135px;
}

.labelContainer .labelText.labelText_med {
  width: 105px;
}

What I am trying to achieve, that when the Mobile css version kicks in, indifferent of the labelText_size class the labelText should take up all the width it can. If I copy the above three rules, and change the width to 100% in each of them, this works just as intended. But if I try to do the following

.labelContainer .labelText {
  width: 100%;
  height: 32px;
}  

only the height gets changed, and the width stays the same.

I presume this is because the more exact the rule, the higher priority it has, but isn't there a way to tell CSS, that no matter what other classes the DOM element has, apply the desired rule?

Because if I define like 20 different size styles for my labels, I would now have to define the same 20 different size styles in my mobile css too, instead of using a single rule, that overwrites the rest.

EDIT: I know I can achieve the desired result with marking the rule as important, but I would rather not do that, because I don't think that setting something as important is a good practice in css.

Upvotes: 3

Views: 50

Answers (2)

sergdenisov
sergdenisov

Reputation: 8572

You could add any class only for mobile devices on <html> or <body> and use it in your mobile CSS version. For example:

.mobile .labelContainer .labelText {
    width: 100%;
    height: 32px;
}

Upvotes: 1

antyrat
antyrat

Reputation: 27765

You can achieve this by using attribute selectors:

.labelContainer .labelText[class*="labelText_"] {
    width: 100%;
    height: 32px;
}

Upvotes: 2

Related Questions