简体   繁体   中英

SASS mixin with variable as selector

My goal is to style a bunch of input types which requires a lot of code. Most of it is re-used when you are also declaring the various states inputs have.

Is there a method with SASS where you can pass a "state" variable to a mixin, and then use that mixin as a selector?

Here's my (non-working) code that I was plugging in at https://www.sassmeister.com to test.

@mixin inputs($state) {
  input[type="text"]$state;
  input[type="email"]$state;
  input[type="url"]$state;
  input[type="search"]$state;
  input[type="date"]$state;
  input[type="time"]$state;
  /* etc */
}

@include inputs() {
  border:2px solid #ccc;
}

@include inputs(:hover) {
   border:2px solid #000;
}

@include inputs(:focus) {
   border:2px solid blue;
}

@include inputs(:active) {
   border:2px solid red
}

You can do this without a mixin by using the sass ampersand .

input[type="text"],
input[type="email"],
input[type="url"],
input[type="search"],
input[type="date"],
input[type="time"] {
  border:2px solid #ccc;
  &:hover {
    border:2px solid #000;
  }
  &:focus {
    border:2px solid blue;
  }
  &:active {
    border:2px solid red;
  }
}

You're misusing the mixins, as stated in the sass documentation, mixins must contain declarations.

Some things in CSS are a bit tedious to write, especially with CSS3 and the many vendor prefixes that exist. A mixin lets you make groups of CSS declarations that you want to reuse throughout your site. You can even pass in values to make your mixin more flexible. A good use of a mixin is for vendor prefixes. Here's an example for transform.

So having mixins containing no value for their property will create an error.

If you revert the logic it will work. You can add more variables to my example as well, say for border size or type.

@mixin inputBorder($color) {
  border: 2px solid $color;
}

input[type="text"],
input[type="email"],
input[type="url"],
input[type="search"],
input[type="date"],
input[type="time"] {
  @include inputBorder(#ccc);

  &:hover {
   @include inputBorder(#000);
  }

  &:focus {
   @include inputBorder(blue);
  } 

  &:active {
   @include inputBorder(red);
  }
}

You can also use @josephWebber example if you only want to change the border color.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM