Home >Web Front-end >CSS Tutorial >How can I create an efficient placeholder mixin in SCSS/CSS that handles nested and unnested selectors?
Placeholder Mixin in SCSS/CSS
When creating a SASS mixin for placeholders, a simple mixin like the one below might not suffice due to the number of colons and semi-colons that are passed through to it:
<code class="scss">@mixin placeholder ($css) { ::-webkit-input-placeholder {$css} :-moz-placeholder {$css} ::-moz-placeholder {$css} :-ms-input-placeholder {$css} }</code>
Using @content Directive
To pass static CSS through to a mixin exactly as desired, the @content directive can be used. Here's an example:
<code class="scss">@mixin placeholder { ::-webkit-input-placeholder {@content} :-moz-placeholder {@content} ::-moz-placeholder {@content} :-ms-input-placeholder {@content} } @include placeholder { font-style:italic; color: white; font-weight:100; }</code>
More information can be found in the SASS Reference at https://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#mixin-content.
Optional @-root Mixin (Sass 3.4 and above)
In Sass 3.4 and above, the optional-at-root mixin can be used to handle nested and unnested selectors effectively:
<code class="scss">@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; } }</code>
Usage:
<code class="scss">.foo { @include placeholder { color: green; } } @include placeholder { color: red; }</code>
Output:
<code class="css">.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; }</code>
The above is the detailed content of How can I create an efficient placeholder mixin in SCSS/CSS that handles nested and unnested selectors?. For more information, please follow other related articles on the PHP Chinese website!