Skip to content

Instantly share code, notes, and snippets.

@antsa
Created March 23, 2012 12:00
Show Gist options
  • Star 33 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save antsa/2170024 to your computer and use it in GitHub Desktop.
Save antsa/2170024 to your computer and use it in GitHub Desktop.
Placeholder mixin for Sass
// Placeholder @mixin for Sass
//
// A mixin to style placeholders in HTML5 form elements.
// Includes also a .placeholder class to be used with a polyfill e.g.
// https://github.com/mathiasbynens/jquery-placeholder
// Requires Sass 3.2.
//
// Example usage (.scss):
//
// input {
// @include placeholder {
// /* styles for placeholder here */
// }
// }
//
@mixin placeholder {
&.placeholder { @content }
&:-moz-placeholder { @content }
&::-webkit-input-placeholder { @content }
}
@salarmehr
Copy link

@mixin placeholder {
  &.placeholder { @content; }
  &:-moz-placeholder { @content; }
  &::-moz-placeholder { @content; }
  &::-webkit-input-placeholder { @content; }
}

@srsgores
Copy link

srsgores commented Sep 6, 2013

@mixin placeholder {
    &::-webkit-input-placeholder {
        @content;
    }

    &:-moz-placeholder { /* Firefox 18- */
        @content;
    }

    &::-moz-placeholder {  /* Firefox 19+ */
        @content;
    }

    &:-ms-input-placeholder {
        @content;
    }
}

@jwwicks
Copy link

jwwicks commented Jul 14, 2019

From Bourbon...

  @mixin placeholder {
    $placeholders: ":-webkit-input" ":-moz" "-moz" "-ms-input";
    @each $placeholder in $placeholders {
      &:#{$placeholder}-placeholder {
        @content;
      }
    }
  }

@pvrt
Copy link

pvrt commented Nov 20, 2019

In Sass 3.4 you can use this snippet to work both nested and unnested rules

@mixin optional-at-root($sel) {
  @at-root #{if(not &, $sel, selector-append(&, $sel))} {
    @content;
  }
}

@mixin placeholder {
  @include optional-at-root('::-webkit-input-placeholder') {
    @content;
  }

  @include optional-at-root(':-moz-placeholder') {
    @content;
  }

  @include optional-at-root('::-moz-placeholder') {
    @content;
  }

  @include optional-at-root(':-ms-input-placeholder') {
    @content;
  }
}

Usage:

.foo {
  @include placeholder {
    color: green;
  }
}

@include placeholder {
  color: red;
}

Output:

.foo::-webkit-input-placeholder {
  color: green;
}
.foo:-moz-placeholder {
  color: green;
}
.foo::-moz-placeholder {
  color: green;
}
.foo:-ms-input-placeholder {
  color: green;
}

::-webkit-input-placeholder {
  color: red;
}
:-moz-placeholder {
  color: red;
}
::-moz-placeholder {
  color: red;
}
:-ms-input-placeholder {
  color: red;
}

From this question https://stackoverflow.com/a/17181946

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment