首页 > 解决方案 > 将媒体查询定义为变量

问题描述

我有以下简单代码HTMLCSS代码media queries,您也可以在JSfiddle 此处找到:

/* Screenwidth as variable */

:root {
  --min-width: 1041px;
}


/* homepage */

@media screen and (min-width:1041px){ 
 
 .homepage {
 height: 500px;
 width: 400px;
 }
 
}
  
  
@media screen and (max-width:1040px){ 
   
 .homepage {
 height: 300px;
 width: 100px;
 } 
   
}


/* faq */

@media screen and (min-width:1041px){ 
 
 .faq {
 height: 800px;
 width: 600px;
 }

}
  
  
@media screen and (max-width:1040px){ 
   
 .faq {
 height: 700px;
 width: 550px;
 } 
   
}
<div class="homepage">
Here goes content of homepage.
</div>

<div class="faq">
Here goes content of faq.
</div>

正如您在代码中看到的那样,我的网站上会有不同的页面,并且它们应该具有不同的大小,具体取决于访问网站的设备。它media queries本身已经完美地工作了。


但是,由于我的 CSS 中有很多这样的内容,并且我可能希望将它们更改为不同的大小以进行测试和尝试,因此在 CSS的一部分中包含 the和asmedia queries会很棒。min-widthmax-widthvariable:root

你知道这是否可能,如果是的话,我必须如何更改我的代码才能使其工作?

标签: htmlcssmedia-queries

解决方案


不,您不能在媒体查询中使用 css 本机变量。

The :root, that is the element is a top-level parent. The other child elements can inherit from the root but the media query is not an element,

This can't be done through css. you can use preprocessors like sass to accomplish this.


推荐阅读