【问题标题】:Math with interpolated variables?带有插值变量的数学?
【发布时间】:2012-01-05 11:56:47
【问题描述】:

考虑以下 sass:

$font-size: 18;                 
$em: $font-size;

$column: $font-size * 3;        // The column-width of my grid in pixels
$gutter: $font-size * 1;        // The gutter-width of my grid in pixels

$gutter-em: #{$gutter / $em}em; // The gutter-width in ems.
$column-em: #{$column / $em}em; // The column-width in ems;

$foo = $gutter-em / 2; // This results in a value like "1em/2". :(
$bar = ($gutter-em / 2); // this doesn't work either, same as above.

如何生成一个有效的$foo,并且可以在其他表达式中进一步重用?

【问题讨论】:

    标签: sass


    【解决方案1】:

    Sass 不能对字符串执行算术运算,只能进行连接。当您使用插值时,您创建的是一个 看起来 像数字的字符串:

    @debug type-of(#{10px});         // string
    @debug type-of('10px');          // string
    @debug type-of(unquote('10px')); // string
    @debug type-of(10px);            // number
    

    如果你想要一个数字,不要使用插值,也不要使用引号。要将整数(例如10)转换为长度(例如10px),请使用乘法:

    $gutter-em: ($gutter / $em) * 1em;
    @debug type-of($gutter-em);      // number
    

    【讨论】:

    • 伙计,我没有看到这个我觉得很愚蠢。感谢您的快速答复!
    • 插值颜色怎么样?例如,3 是我的循环迭代器,我想创建一个样式,显示 background-color: #333;如何放置 # 而不将其转换为字符串?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    • 2018-09-26
    • 1970-01-01
    相关资源
    最近更新 更多