较少 - 将媒体查询规则与相同条件相结合

时间:2015-08-31 06:27:14

标签: css less media-queries

我使用以下LESS mixin来优化2x屏幕的背景图像。

定义::

.image-2x(@image, @width: auto, @height: auto, @repeat: no-repeat) {
  @filename  : ~`/(.*)\.(jpg|jpeg|png|gif)/.exec(@{image})[1]`;
  @extension : ~`/(.*)\.(jpg|jpeg|png|gif)/.exec(@{image})[2]`;
  background-image: ~`"url(@{filename}.@{extension})"`;
  background-repeat: @repeat;
  background-size: @width @height;
  @media
    only screen and (-webkit-min-device-pixel-ratio: 2),
    only screen and (   min--moz-device-pixel-ratio: 2),
    only screen and (        min-device-pixel-ratio: 2),
    only screen and (                min-resolution: 192dpi),
    only screen and (                min-resolution: 2dppx) {
      background-image: ~`"url(@{filename}@2x.@{extension})"`;
    }
  }
}

使用::

selector1 {
  .image-2x("path/to/image1.png"); 
}
selector2 {
  .image-2x("path/to/image2.png"); 
}

输出:

selector1 {
  background-image: url(path/to/image1.png);
  background-repeat: no-repeat;
  background-size: auto auto;
}
@media
  only screen and (-webkit-min-device-pixel-ratio: 2),
  only screen and (   min--moz-device-pixel-ratio: 2),
  only screen and (        min-device-pixel-ratio: 2),
  only screen and (                min-resolution: 192dpi),
  only screen and (                min-resolution: 2dppx) {
    selector1 {
      background-image: url(path/to/image1@2x.png);
    }
  }
}
selector2 {
  background-image: url(path/to/image2.png);
  background-repeat: no-repeat;
  background-size: auto auto;
}
@media
  only screen and (-webkit-min-device-pixel-ratio: 2),
  only screen and (   min--moz-device-pixel-ratio: 2),
  only screen and (        min-device-pixel-ratio: 2),
  only screen and (                min-resolution: 192dpi),
  only screen and (                min-resolution: 2dppx) {
    selector2 {
      background-image: url(path/to/image2@2x.png);
    }
  }
}

最佳输出::

selector1 {
  background-image: url(path/to/image1.png);
  background-repeat: no-repeat;
  background-size: auto auto;
}
selector2 {
  background-image: url(path/to/image2.png);
  background-repeat: no-repeat;
  background-size: auto auto;
}
@media
  only screen and (-webkit-min-device-pixel-ratio: 2),
  only screen and (   min--moz-device-pixel-ratio: 2),
  only screen and (        min-device-pixel-ratio: 2),
  only screen and (                min-resolution: 192dpi),
  only screen and (                min-resolution: 2dppx) {
    selector1 {
      background-image: url(path/to/image1@2x.png);
    }
    selector2 {
      background-image: url(path/to/image2@2x.png);
    }
  }
}

为实现这一目标,我想到将@ 2x背景图片网址存储在列表中,然后在一个媒体查询中打印文件末尾的所有已保存规则集。但是我找不到办法去做。

任何人都可以提出解决方案,我对任何方法都很好。

我正在使用grunt-contrib-less编译我的更少。如果任何编译器优化输出,请提及它。

0 个答案:

没有答案