2017-07-16 164 views
3

我试图在CSS/scss中构建自己的小型可缩放网格。 到目前为止,我发现了这个决定:如何将CSS变量值分配给scss变量或表达式

:root { 
    --page-width: 1170px; 
    --gutter: 15px; 
    --columns: 12; 
} 

.wrapper { 
    max-width: var(--page-width); 
    margin-right: auto; 
    margin-left: auto; 
    padding-left: var(--gutter); 
    padding-right: var(--gutter); 
} 

.row { 
    margin-left: calc(-1 * var(--gutter)); 
    margin-right: calc(-1 * var(--gutter)); 
} 

.col { 
    display: block; 
    margin-left: var(--gutter); 
    margin-right: var(--gutter); 
} 

然后我试图使用SCSS缩短列类说明(在同一时间让我改变在整个代码一个位置列数 - 在CSS变量--columns)像这样

@for $n from 1 through var(--columns) { 
    .col-#{$n} {width: calc(#{$n}/var(--columns) - var(--gutter) * 2); } 
} 

但它没有工作。有趣的细节是,当我改变从@for $n from 1 throughvar(--columns)``到@for $n from 1 through12@for声明它编译好。在@for内部编译CSS-Variable没有问题。 .col-#{$n} {width: calc(#{$n}/var(--columns) - var(--gutter) * 2); }很好地编译成需要的一系列类。

如果我使用scss变量$columns而不是CSS变量,那么我需要将我的grid.scss文件导入到项目的所有其他scss文件中。

这是我在StackOverflow上的第一个问题,所以让我知道是否需要其他细节。

+0

的可能的复制[如何在CSS变量强制整数?](https://stackoverflow.com/questions/44524527/how-to-force-integer-in-css-variable) –

+0

Saurabh Gour,实际上,是的。你提出的问题涵盖了我的问题。但我永远不会在它的当前标题“如何在CSS变量中强制整数”下找到它。 –

+0

我几乎按下了'这解决了我的问题!'按钮,但是然后我阅读了解释消息。它说:“这将标记你的问题是重复的,指导未来的读者原来的问题,并防止在这里发布进一步的答案。” 我不介意将我的问题标记为一般重复的问题。但在这个具体的例子中,我认为'如何在CSS变量中强制整数'不是重点,也不是主要主题。我的问题会保持可见吗?还是会隐藏?重定向将如何发生? –

回答

3

CSS和SCSS变量是两个完全不同的东西(请参阅this pen

为了使它工作,你需要一个静态变量SCSS编译

// static (SCSS) variables used produce CSS output 
$page-width: 1170px; 
$gutter : 15px 
$columns: 12; 

// dynamic (CSS) variables used at run-time 
:root { 
    --page-width: $page-width; 
    --gutter : $gutter; 
    --columns: $columns; 
} 

// the for loop is aimed at producing CSS output 
// ... why you need the static variable 
@for $n from 1 through $columns { 

    // the content becomes CSS output 
    // ... why you can use dynamic variables 
    .col-#{$n} {width: calc(#{$n}/var(--columns) - var(--gutter) * 2); } 

} 
+1

Jacob E,非常感谢。你的解决方案为我工作。另外,我查看了你的笔,这给了我更多的理解。 –

1

您需要对变量使用插值(例如#{$ var}),以便Sass将其视为CSS属性。没有它,你只是在执行变量赋值。

@mixin w_fluid($property_name, $w_element, $w_parent:16) { #{$property_name}: percentage(($w_element/$w_parent)); }