Home > Web Front-end > CSS Tutorial > How to Style Placeholder Text using a Mixin in SCSS/CSS?

How to Style Placeholder Text using a Mixin in SCSS/CSS?

Susan Sarandon
Release: 2024-10-26 13:34:30
Original
1024 people have browsed it

How to Style Placeholder Text using a Mixin in SCSS/CSS?

Placeholder Mixin in SCSS/CSS

Challenge:
Create a mixin to style placeholder text using static CSS within Sass.

Mixin Attempt:

<code class="scss">@mixin placeholder ($css) {
  ::-webkit-input-placeholder {$css}
  :-moz-placeholder           {$css}
  ::-moz-placeholder          {$css}
  :-ms-input-placeholder      {$css}  
}</code>
Copy after login

Problem:
The mixin does not work due to colons and semicolons passed through the $css parameter, interfering with browser-specific placeholder selectors.

Solution: Using @content Directive
Introduce the @content directive to include static CSS within the mixin without disrupting the placeholder selectors.

<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>
Copy after login

Further Enhancement: Nested and Unnested Usage (Sass 3.4 )

<code class="scss">@mixin optional-at-root($sel) {
  @at-root #{if(not &amp;, $sel, selector-append(&amp;, $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>
Copy after login

This allows you to nest the placeholder mixin within other selectors while still targeting the placeholder element.

The above is the detailed content of How to Style Placeholder Text using a Mixin in SCSS/CSS?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template