本文介绍了使用在媒体查询中设置的类为mixin in less的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图重用一组在媒体查询中设置的类作为mixins在整个网站中使用,而不是在html中嵌入非语义类名。

I am trying to reuse a set of classes set inside a media query as mixins to use throughout a website instead of embedding un-semantic class names in html.

这是我的问题的一个例子。

Here is an example of my problem.

@media (min-width: 1000px) {

    .foo{width:120px;}
    .foo-2{width:150px;}
}
@media (max-width: 999px) {

    .foo{width:110px;}
    .foo-2{width:120px;}
}

.bar{.foo;}
.bar-2{.foo;}
.bar-3{.foo-2;}

bar-X永远不会得到任何样式。我可以猜测,这是因为LESS不在媒体查询中创建.bar-X,因此不会应用任何内容。

the .bar-X will never get any styles applied. I can guess that this is happening because LESS doesn't create .bar-X inside media queries, so nothing will ever be applied.

这是LESS中的一个错误,或者我永远不能实现的东西?解决方法是理想的。

Is this a bug in LESS, or something I can never achieve? A workaround to this would be ideal.

推荐答案

您的问题是一个常见的误解。 LESS不会处理 @media 查询,浏览器会在LESS完成其工作后进行 。 LESS只能创建浏览器要读取的CSS代码。因此, @media 对LESS是无意义的,它就像任何其他选择器( .someClass div表等等),它只处理要向浏览器提供的 @media

Your problem is a common misconception. LESS does not process the @media query, the browser does after LESS has done its work. LESS can only create the CSS code that the browser is going to read. So the @media is "meaningless" to LESS, it is just like any other selector (.someClass div table, etc.), it only processes what the @media is going to serve to the browser.

您需要将所有您对 @media 所做的更改的代码放在 @media 块中。但是你也不想要一堆重复的代码。所以,创建一个主混合来设置您的 @media 代码,然后从媒体查询调用该mixin:

So that means you need to put all your code that changes for the @media in the @media block. But you also don't want a bunch of repeated code. So instead, create a master mixin to set your @media code, and then call that mixin from the media queries:

.makeFooGroup(@w1, @w2) {
    .foo {width: @w1}
    .foo-2{width: @w2}
    .bar{.foo}
    .bar-2{.foo}
    .bar-3{.foo-2}
}

@media (min-width: 1000px) {
    .makeFooGroup(120px, 150px);
}
@media (max-width: 999px) {
    .makeFooGroup(110px, 120px);
}

产生此css:

@media (min-width: 1000px) {
  .foo {width: 120px;}
  .foo-2 {width: 150px;}
  .bar {width: 120px;}
  .bar-2 {width: 120px;}
  .bar-3 {width: 150px;}
}
@media (max-width: 999px) {
  .foo {width: 110px;}
  .foo-2 {width: 120px;}
  .bar {width: 110px;}
  .bar-2 {width: 110px;}
  .bar-3 {width: 120px;}
}

有关与此有关的LESS和 @media 的更多信息,请参阅:

For some further info I've given on LESS and @media related to this, see:




  1. CSS pre-processor with a possibility to define variables in a @media query
  2. Media Query grouping instead of multiple scattered media queries that match

这篇关于使用在媒体查询中设置的类为mixin in less的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-09 22:27