Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

BernardoBF4's avatar

Applying DRY when styling with @media queries and Sass

I have been wondering about what's the best way to style with Sass and @media in a way to be DRY. I have a piece of code where I have decided to put the @medias inside each child of the class, like this (the @include m. are the @media):

.ui-field {
  display: flex;
  flex-direction: column;
  width: 100%;
  & label {
    color: c.$lead;
    @include s.font(16, 600);
    @include m.desktop-down {
      @include s.font(14, 600);
    }
  }
  & p {
    color: c.$red;
    @include s.font(15);
    @include m.desktop-down {
      @include s.font(14, 600);
    }
  }
  & select {
    appearance: auto;
  }
  & span {
    color: c.$dark-gray;
    @include s.font(16);
    text-align: end;
    @include m.desktop-down {
      @include s.font(14);
    }
  }
}

I do understand that maybe moving all the @medias to the bottom of the class block and putting all the child with their CSS rules would be visually better, but I also think about the possibility of having to change my HTML structure, and thus having to change my CSS, what would obligate me to change two structures: one on the "normal" block and the other on the @media block. So it seems like it all comes down to repeating selectors or repeating @medias.

As of Sass, I know it's great for reducing code, but I don't know if it can solve this problem; maybe with some clever technique or something like that, but that's what I am hopping you could say.

0 likes
1 reply
LaryAI's avatar
Level 58

One solution to make the code more DRY is to extract the common styles outside of the media queries and use variables to store the values that change between the media queries. Here's an example:

$label-font-size: 16px;
$p-font-size: 15px;
$span-font-size: 16px;

.ui-field {
  display: flex;
  flex-direction: column;
  width: 100%;

  & label {
    color: c.$lead;
    @include s.font($label-font-size, 600);
  }

  & p {
    color: c.$red;
    @include s.font($p-font-size);
  }

  & select {
    appearance: auto;
  }

  & span {
    color: c.$dark-gray;
    @include s.font($span-font-size);
    text-align: end;
  }

  @include m.desktop-down {
    & label {
      @include s.font(14, 600);
    }

    & p {
      @include s.font(14, 600);
    }

    & span {
      @include s.font(14);
    }
  }
}

In this example, we define variables for the font sizes that change between the media queries. Then, we extract the common styles outside of the media queries and use the variables to set the font sizes. Finally, we apply the media queries to the entire block of styles, instead of repeating them for each child element.

This approach makes the code more DRY and easier to maintain, as we only need to change the values of the variables to update the styles for all the media queries.

Please or to participate in this conversation.