我想要一个变量,其中包含 CSS 文件中所有图像的根路径。我不太清楚这在纯 Sass 中是否可行(实际的 Web 项目不是 RoR,因此不能使用 asset_pipeline 或任何花哨的爵士乐)。
这是我的例子,但不起作用。编译时,它会在后台 url 属性中的第一个变量实例上犹豫不决,并显示 (
"Invalid CSS after "..site/background": expected ")"
)。
定义返回路径的函数:
//Vars
$assetPath : "/assets/images";
//Functions
@function get-path-to-assets($assetPath){
@return $assetPath;
}
使用功能:
body {
margin: 0 auto;
background: url($get-path-to-assets/site/background.jpg) repeat-x fixed 0 0;
width: 100%; }
如有任何帮助,我们将不胜感激。
您尝试过Interpolation语法吗?
background: url(#{$get-path-to-assets}/site/background.jpg) repeat-x fixed 0 0;
不需要函数:
$assetPath : "/assets/images";
...
body {
margin: 0 auto;
background: url(#{$assetPath}/site/background.jpg) repeat-x fixed 0 0;
width: 100%; }
有关详细信息,请参阅插值文档。
正在寻找同一问题的答案,但我认为我找到了更好的解决方案:https://web.archive.org/web/20140927161149/http://blog.grayghostvisuals.com/compass/image-url /
基本上,您可以在 config.rb 中设置图像路径并使用 image-url() 帮助器
在上面的正确答案中添加一些内容。我正在使用 netbeans IDE,并且在使用
url(#{$assetPath}/site/background.jpg)
此方法时显示错误。这只是netbeans错误,sass编译没有错误。但是这个错误破坏了 netbeans 中的代码格式,并且代码变得丑陋。但是当我像下面这样在引号内使用它时,它会显示出奇迹!
url("#{$assetPath}/site/background.jpg")
我们可以使用相对路径代替绝对路径:
$assetPath: '~src/assets/images/';
$logo-img: '#{$assetPath}logo.png';
@mixin logo {
background-image: url(#{$logo-img});
}
.logo {
max-width: 65px;
@include logo;
}