CSS 在 Sass 的图像路径中有一个变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8608498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 02:28:04  来源:igfitidea点击:

Have a variable in images path in Sass?

csssass

提问by program247365

I want to have one variable that contains the root path to all my images in my CSS file. I can't quite figure out if this is possible in pure Sass (the actual web project is not RoR, so can't use asset_pipeline or any of that fancy jazz).

我希望有一个变量包含我的 CSS 文件中所有图像的根路径。我不太清楚这在纯 Sass 中是否可行(实际的 Web 项目不是 RoR,因此不能使用 asset_pipeline 或任何花哨的爵士乐)。

Here's my example that doesn't work. On compile it balks at first instance of variable in the background url property saying ("Invalid CSS after "..site/background": expected ")").

这是我不起作用的例子。在编译时,它在后台 url 属性中的第一个变量实例中犹豫不决,说 ( "Invalid CSS after "..site/background": expected ")")。

Defining the function to return the path:

定义返回路径的函数:

//Vars
$assetPath : "/assets/images";

//Functions
@function get-path-to-assets($assetPath){
  @return $assetPath;
}

Using the function:

使用功能:

body {
  margin: 0 auto;
  background: url($get-path-to-assets/site/background.jpg) repeat-x fixed 0 0;
  width: 100%; }

Any help would be appreciated.

任何帮助,将不胜感激。

回答by Wesley Murch

Have you tried the Interpolationsyntax?

您是否尝试过插值语法?

background: url(#{$get-path-to-assets}/site/background.jpg) repeat-x fixed 0 0;

回答by steveax

No need for a function:

不需要函数:

$assetPath : "/assets/images";

...

body {
  margin: 0 auto;
  background: url(#{$assetPath}/site/background.jpg) repeat-x fixed 0 0;
  width: 100%; }

See the interpolation docsfor details.

有关详细信息,请参阅插值文档

回答by NerdCowboy

Was searching around for an answer to the same question, but think I found a better solution: http://blog.grayghostvisuals.com/compass/image-url/

正在四处寻找同一问题的答案,但认为我找到了更好的解决方案:http: //blog.grayghostvisuals.com/compass/image-url/

Basically, you can set your image path in config.rb and you use the image-url() helper

基本上,您可以在 config.rb 中设置图像路径并使用 image-url() 助手

回答by Pons Purushothaman

Adding something to the above correct answers. I am using netbeans IDE and it shows error while using url(#{$assetPath}/site/background.jpg)this method. It was just netbeans error and no error in sass compiling. But this error break code formatting in netbeans and code become ugly. But when I use it inside quotes like below, it show wonder!

在上述正确答案中添加一些内容。我正在使用 netbeans IDE,它在使用url(#{$assetPath}/site/background.jpg)此方法时显示错误。这只是 netbeans 错误,而 sass 编译没有错误。但是这个错误会破坏 netbeans 中的代码格式并且代码变得丑陋。但是当我在下面的引号中使用它时,它显示出奇迹!

url("#{$assetPath}/site/background.jpg")

url("#{$assetPath}/site/background.jpg")