如何重构媒体查询中常见的 css 规则?

How to refactor common css rules in media queries?

我正在定义几个媒体查询,并且有一些重复的代码:

@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;
  }
}

那里,唯一改变的规则是 ico-lnb-valid--over-img 中的 left

很可能我必须为不同的媒体查询添加一些其他规则,但是从并使用一些已经定义的代码开始。

我该如何重构它?

只需将重复项从媒体查询中移出,将左侧的保留在 属性 中。您不必使用媒体查询,除非它是您尝试实现的目标所必需的。

@user8424881 是正确的——只有那些与一个媒体查询不同的东西才需要包含在媒体查询中。

代码可以如下所示:

/* 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);
  }
}

只需将重复项排除在媒体查询之外。

.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) {

      .ico-lnb-valid--over-img {
            calc(100% - 47px);
       }
}