我可以在媒体查询中更新SASS变量吗? [英] Can I update SASS variables in Media Queries?
问题描述
请考虑以下SASS代码.我想确保如果屏幕在1250px
以上,则margin-top
应该是750px
,然后它应该根据大小而变化.但是SASS不允许我更新字符串中的变量.
Consider the following SASS code. I want to make sure that if the screen is above 1250px
then the margin-top
should be 750px
and then it should change depending on size. However SASS does not allow me to update the variables inside the strings.
// Above 1250px
$pageTemplateMargin:750px;
// Below 1250px
@media screen and (max-width:1250px){
$pageTemplateMargin:550px;
}
// Below 950px
@media screen and (max-width:950px){
$pageTemplateMargin:450px;
}
@media screen and (max-width:850px){
$pageTemplateMargin:150px;
}
@media screen and (max-width:750px){
$pageTemplateMargin:250px;
}
// Render the correct code
.page-template {margin-top:$pageTemplateMargin}
有没有更好的方法,因为它不起作用并且page-template
停留在750px
.
Is there a better way for this, as it does not work and page-template
stays at 750px
.
谢谢
推荐答案
我同意接受的答案,在这种情况下最好使用maps
,但我想指出几点.
I agree with the accepted answer that it's better to use maps
in this case but I want to point out a couple of things.
实际上可以在媒体查询中更新变量.问题在于,在块外定义的变量是 global 变量,而在块内定义的变量是 local 变量.您可以使用!global 关键字让sass将块中的变量视为全局变量.
Variables can actually be updated inside of media queries. The problem is that a variable defined outside of a block is a global variable while one defined within a block is a local variable. You can let sass treat a variable within a block as a global variable using the !global keyword.
$pageTemplateMargin:750px;
@media screen and (max-width:1250px){
$pageTemplateMargin: 550px !global;
}
.page-template {
margin-top: $pageTemplateMargin //will use 550px instead of 750px
}
仅想澄清一下,尽管在这种用例中不合适,但还是有可能的.
Just want to clarify that it is possible albeit it is not appropriate in this use case.
我还建议对代码使用loop
,这将证明是有帮助的,特别是如果您添加更多的屏幕宽度和边距属性,因此您无需进一步编写更多的媒体查询.
I also suggest using a loop
for your code which will prove helpful especially if you add more screen widths and margin properties so you don't need to further write more media queries.
$breakpoints: (
1200px: 10px,
1000px: 15px,
800px: 20px,
);
@each $width, $margin in $breakpoints {
@media screen and (max-width: $width) {
.element {
margin-top: $margin;
}
}
}
希望这会有所帮助.
这篇关于我可以在媒体查询中更新SASS变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!