Search code examples
cssmedia-queries

How to refactor common css rules in media queries?


I'm defining a couple of media queries, and I'm having some duplicated code:

@media only screen and (max-width:768px) {
  .list__figure {
    margin-right: 20px;
    width: 80px;
  }
  .list__content {
    width: calc(100% - 100px);
  }
  .ico-bim--over-img {
    left: 5px;
    right: inherit;
    top: 5px;
  }
  .ico-lnb-valid--over-img {
    left: 78px;
    top: 5px;
  }
}
@media only screen and (min-width:769px) and (max-width:1040px) {
  .list__figure {
    margin-right: 20px;
    width: 80px;
  }
  .list__content {
    width: calc(100% - 100px);
  }
  .ico-bim--over-img {
    left: 5px;
    right: inherit;
    top: 5px;
  }
  .ico-lnb-valid--over-img {
    left: calc(100% - 47px);
    top: 5px;
  }
}

There, the only rule that changes is for left in ico-lnb-valid--over-img.

Most probably I'll have to add some other rules for different media queries, but start from and using some of the code already defined.

How can I refactor this?


Solution

  • @user8424881 is correct -- only those things that differ from one media query to another need be included within the media queries.

    The code can look like this:

    /* No media queries needed */
    
    .list__figure {
      margin-right: 20px;
      width: 80px;
    }
    .list__content {
      width: calc(100% - 100px);
    }
    .ico-bim--over-img {
      left: 5px;
      right: inherit;
      top: 5px;
    }
    .ico-lnb-valid--over-img {
      top: 5px;
    }
    
    /* Media queries below */
    
    @media only screen and (max-width:768px) {
       .ico-lnb-valid--over-img {
        left: 78px;
      }
    }
    @media only screen and (min-width:769px) and (max-width:1040px) {
      .ico-lnb-valid--over-img {
        left: calc(100% - 47px);
      }
    }