我试图结合使用Sass变量与@media查询,如下所示:
$base_width:1160px;
@media screen and (max-width: 1170px) {$base_width: 960px;}
@media screen and (min-width: 1171px) {$base_width: 1160px;}
然后在基于样式表宽度百分比的度量中的各个点定义
$base_width
,以生成流畅的布局。当我这样做时,似乎可以正确识别该变量,但不能进行媒体查询的条件。例如,上面的代码生成1160px的布局,而不考虑屏幕的宽度。如果我像这样翻转@media语句:
@media screen and (min-width: 1171px) {$base_width: 1160px;}
@media screen and (max-width: 1170px) {$base_width: 960px;}
无论屏幕宽度如何,它都会产生960px的布局。还要注意,如果我删除
$base_width: 1160px;
的第一行,它将为未定义的变量返回错误。有什么想法我想念的吗?
最佳答案
这根本不可能。由于触发器@media screen and (max-width: 1170px)
发生在客户端。
只有在SASS捕获样式表中包含$base_width
变量的所有规则和属性并据此进行复制/更改后,才能实现预期的结果。
由于它不会自动运行,因此您可以手动执行以下操作:
@media screen and (max-width: 1170px)
$base_width: 960px // you need to indent it to (re)set it just within this media-query
// now you copy all the css rules/properties that contain or are relative to $base_width e.g.
#wrapper
width: $base_width
...
@media screen and (min-width: 1171px)
$base_width: 1160px
#wrapper
width: $base_width
...
这不是真正的DRY,而是您能做的最好的事情。
如果每次更改都相同,那么您还可以准备一个包含所有更改值的mixin,因此您无需重复该操作。此外,您可以尝试将mixin与特定更改结合在一起。喜欢:
@media screen and (min-width: 1171px)
+base_width_changes(1160px)
#width-1171-specific-element // additional specific changes, that aren't in the mixin
display: block
而Mixin看起来像这样
=base_width_changes($base_width)
#wrapper
width: $base_width
关于sass - 在CSS3媒体查询中使用Sass变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57560985/