Alexandr Lazarev
Alexandr Lazarev

Reputation: 12882

Generate with the help of gulp-spritesmith property of a :hover rule instead of a class selector

I am using gulp-spritesmith to generate my sprite, and I face a problem: I want some of the generated styles to be properties for hover rules, not for a class selectors. Adding class on mouseover event looks ugly, and I don't consider it as a solution.

For example:

.icon-sr_ext_icon_right {
  background-image: url(/imgs/static/external_sprite.png);
  background-position: -300px -100px;
  width: 50px;
  height: 50px;
}
.icon-sr_ext_icon_right_hovered {
  background-image: url(/imgs/static/external_sprite.png);
  background-position: -222px -200px;
  width: 50px;
  height: 50px;
}

To be:

.icon-sr_ext_icon_right {
  background-image: url(/imgs/static/external_sprite.png);
  background-position: -300px -100px;
  width: 50px;
  height: 50px;
}
.icon-sr_ext_icon_right:hover{
  background-image: url(/imgs/static/external_sprite.png);
  background-position: -222px -200px;
  width: 50px;
  height: 50px;
}

Here is my gulp task code:

gulp.task('external_sprite', function() {
    var spriteData =
        gulp.src(paths.external.sprite)
            .pipe(plugins.debug( { title: "Processing image for external sprite:" } ) )
            .pipe(plugins.spritesmith({
                imgName: 'external_sprite.png',
                imgPath: '/imgs/static/external_sprite.png',
                cssName: 'external_sprite.css'
            }));

    spriteData.img.pipe(gulp.dest('./www/imgs/static/'));
    spriteData.css.pipe(gulp.dest('./' + paths.external.src)); 
});

Upvotes: 5

Views: 777

Answers (1)

Alexandr Lazarev
Alexandr Lazarev

Reputation: 12882

I've found a way how to automatically create styles for hover effects, using sass technology. Simply, generate sprite, than import generated css to another sass file and extend needed class:

@import 'external_sprite';
.icon-sr_ext_icon_right:hover {
    @extend .icon-sr_ext_icon_right_hovered;
}

Another way is suggested by the main contributor of the plugin in the issue on github. The idea is to use cssOpts.cssClass:

cssOpts: {
  cssSelector: function (item) {
    // If this is a hover sprite, name it as a hover one (e.g. 'home-hover' -> 'home:hover')
    if (item.name.indexOf('-hover') !== -1) {
      return '.sprite-' + item.name.replace('-hover', ':hover');
    // Otherwise, use the name as the selector (e.g. 'home' -> 'home')
    } else {
      return '.sprite-' + item.name;
    }
  }
}

But this solution is not working if you are setting .scss extension of the styles file.

Upvotes: 5

Related Questions