Sass背景图像mixin

sim*_*mes 19 css haml sass compass-sass

我是Sass的新手,但我正在尝试为自己创建一个工作流程.我为我的主题设计生成"颜色包",需要为我的mixin指定以下变量.有一个更好的方法吗?:

// folder,filename,extension,repeat,x-pos,y-pos
@mixin background ($folder:style1, $img:file, $type:png, $repeat:no-repeat, $x:0, $y:0) {
    background-image: url(./images/#{$folder}/#{$img}.#{$type});
    background-repeat: #{$repeat};
    background-position: #{$x}px #{$y}px;
}
Run Code Online (Sandbox Code Playgroud)

我这样插入:

#nav {
  @include background(style2,myimage,png,repeat-x,10,10);
}
Run Code Online (Sandbox Code Playgroud)

产生这个:

#nav {
  background-image: url(./images/style2/myimage.png);
  background-repeat: repeat-x;
  background-position: 10px 10px;
}
Run Code Online (Sandbox Code Playgroud)

我希望尽可能使用CSS简写,但我遇到输出错误.如果这不是最好的方法,我会感谢任何专家建议.

Jan*_*nis 31

根据您的包的结构/应用方式,您可以使用循环生成一堆通用样式.请参阅此处的文档:http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#id35

你真的需要3个独立的组件来获取你的图像网址吗?不会:$img然后将其设置为/folder/img.ext更容易?

此外,#{}顺便说一下,你不需要重复.

我希望这就是你所追求的......对于你需要实际结果的问题,问题并不是非常具体.

干杯,詹尼斯

更新:

好的,我看到你已经更新了你的问题(谢谢你).我相信这对于一般用途可能会更好一点:

@mixin background($imgpath,$position:0 0,$repeat: no-repeat) {
    background: {
        image: url($imgpath);
        position: $position;
        repeat: $repeat;
    }
}
.testing {
    @include background('/my/img/path.png');
}
Run Code Online (Sandbox Code Playgroud)

然后输出:

.testing {
  background-image: url("/my/img/path.png");
  background-position: 0 0;
  background-repeat: no-repeat;
}
Run Code Online (Sandbox Code Playgroud)

或者您可以使用速记版本:

@mixin backgroundShorthand($imgpath,$position:0 0,$repeat: no-repeat) {
    background: transparent url(#{$imgpath}) $repeat $position;
}
.testing2 {
    @include backgroundShorthand('/my/img/path.png');
}
Run Code Online (Sandbox Code Playgroud)

这会产生:

.testing2 {
  background: transparent url(/my/img/path.png) no-repeat 0 0;
}
Run Code Online (Sandbox Code Playgroud)

最后,如果要单独指定映像目录的基本路径,可以执行以下操作:

$imagedir:'/static/images/'; // define the base path before the mixin

@mixin backgroundShorthandWithExternalVar($filename,$position:0 0,$repeat: no-repeat) {
    background: transparent url(#{$imagedir}#{$filename}) $repeat $position;
}
.testing3 {
    @include backgroundShorthandWithExternalVar('filename.png');
}
Run Code Online (Sandbox Code Playgroud)

这将生成:

.testing3 {
  background: transparent url(/static/images/filename.png) no-repeat 0 0;
}
Run Code Online (Sandbox Code Playgroud)

这是你需要的吗?

如果没有随时更新问题或回复/评论.