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

我想有一个变量,其中包含根路径的所有图像在我的 CSS 文件。我不能确定这在纯 Sass 中是否可行(实际的 Web 项目不是 RoR,所以不能使用 asset _ management 或任何花哨的爵士乐)。

这是我的例子,但是不起作用。在编译时,它会在后台 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%; }

如果你能帮忙,我将不胜感激。

124451 次浏览

不需要功能:

$assetPath : "/assets/images";


...


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

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

你试过 插值语法吗?

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

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

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

在上述正确答案中添加一些内容。我使用的是 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;
}