J
J
jetfx2021-07-14 13:56:16
css
jetfx, 2021-07-14 13:56:16

How to force media query styles to override nested Less rules(styles)?

I use such a feature of the Less preprocessor as nesting of styles. Very often, for convenience, I set the styles of nested HTML elements also in a nested form, so that you can understand the structure of the page directly from the style file.

Example:

<div class="event">
    <h2 class="event__caption">Игра в футбол</h2>
    <p class="event__description">Сегодня состоится товарищеский матч по футболу</p>
</div>

.event {
    width: 300px;
    height: 100px;
    
    .event__caption {
      color: blue;
    }

    .event__description {
      color: green;
    }
  }


However, there is a problem when I am engaged in adaptive layout. The nested styles of such elements, after compilation, turn into long combined selectors, which are more specific than styles from media queries. Accordingly, if, for example, the color for the title of the event card is redefined in the media query , the new color cannot override the old one. Of course, I included the media query styles after the compiled Less styles. Now I solve this problem by adding !impotant to styles from media queries. I don't want to refuse Less nesting, because it's convenient. Can you please tell me if there is a better way to solve this problem? I feel like I've got a crutch. .event__caption { color: red}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander, 2021-07-14
@jetfx

.event {
  width: 300px;
  height: 100px;
  
  &__caption {
    color: blue;
  }

  &__description {
    color: green;
  }
}

@media screen and (max-width: 768px) {
    .event {
        &__caption {
            color: red;
        }
    }
}

or
.event {
  width: 300px;
  height: 100px;
  
  &__caption {
    color: blue;
    
    @media screen and (max-width: 768px) {
      color: red;
    }
  }

  &__description {
    color: green;
  }
}

I
iBird Rose, 2021-07-14
@iiiBird

write so that there is no nesting:

.event {
    width: 300px;
    height: 100px;
    
    &__caption {
      color: blue;
    }

    &__description {
      color: green;
    }
  }

A
Alexander Sharomet, 2021-07-14
@sharomet

Judging by the code, you are using BEM and messed up something with it (nesting is generally unnecessary here):
BEM:

.event {
    width: 300px;
    height: 100px;
    &__caption {
      color: blue;
    }

    &__description {
      color: green;
    }
}

calmly interrupt in css:
@media(max-width: 767px) {
.event__caption { color: red}
}

If you really need it, you can use !important - it will kill everything, but it should be used only in extreme cases. Or better yet, don't use it at all.
@media(max-width: 767px) {
.event__caption { color: red !important}
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question