【问题标题】:CSS Variables and String concatenationCSS 变量和字符串连接
【发布时间】:2016-11-15 03:15:47
【问题描述】:

我正在尝试使用 CSS 变量来生成动态路径。

示例

:root {
  --fonts-path: "/path/to/font";
}

@font-face {
  font-family: "FontName";
  src: url(var(--fonts-path) + "/FontName-Light.woff") format('woff');
  font-weight: 100;
}

html {
  font-family: 'Metric', Arial, sans-serif;
}

由于未找到模块 'var(--hpe-fonts-path' 而失败,这是 webpack 日志:

ERROR in ./~/css-loader?sourceMap&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!./~/postcss-loader!./src/theme/fonts.css
Module not found: Error: Cannot resolve module 'var(--fonts-path' in /Users/project-sample/src/theme
 @ ./~/css-loader?sourceMap&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!./~/postcss-loader!./src/theme/fonts.css 6:83-114 6:234-265 6:403-434 6:576-607

任何指针?

【问题讨论】:

    标签: css webpack css-variables


    【解决方案1】:

    您不能在 CSS (refer here) 中连接变量:

    由于不能在 CSS 中连接(除了 content 属性),因此不能连接 CSS 变量。这意味着,例如,您不能将作为数字的 CSS 变量与单位相结合。

    // No version of this will work 
    div {
      --height: 100;
      height: var(--height) + 'px';
    }
    

    【讨论】:

      【解决方案2】:

      尝试将 url 包含在变量中,这在后台上下文中有效,但不确定它是否在 font-face 中有效

      :root { 
      --url:url("https://picsum.photos/id/1/200/300"); 
      }
      
      .box { 
      background:var(--url); 
      }
      

      【讨论】:

        【解决方案3】:

        这篇文章描述了一个类似的问题:

        CSS native variables not working in media queries

        用户尝试在@font-face 规则中使用变量。

        如已接受的答案 (https://stackoverflow.com/a/40723269/4879632) 中所述,您不能在规则内使用变量,因为变量由 :root (html) 子元素继承。 @ 规则(字体、媒体查询等)不是元素,因此它们不会从根继承。因此,您不能从那里引用变量。

        【讨论】:

          【解决方案4】:

          我发现您的方法存在一些问题:

          • @font-face 规则不继承 :root 上设置的 CSS 变量。

          • 您不能使用 + 连接 CSS 字符串。见string concatenation in css

          • 并非所有实现都支持url() 内的var()

          【讨论】:

            猜你喜欢
            • 2018-06-23
            • 1970-01-01
            • 2021-12-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-12-17
            相关资源
            最近更新 更多