开发者

How write *::selection{} in scss\sass?

开发者 https://www.devze.com 2023-03-19 20:41 出处:网络
I tried to do the following, but it does not work: * { &::selection { text-decoration: underline; }

I tried to do the following, but it does not work:

* {
    &::selection { text-decoration: underline; }
}
开发者_高级运维


That's the way I do it:

// define it
@mixin selection {
    ::-moz-selection { @content; }
    ::selection { @content; }
}

// use it
@include selection {
    color: white;
    background: black;
}

Update

I recommend to just use ::selection {} with autoprefixer instead of a mixin. This will make your code thinner and your brain lighter :)

In this case, autoprefixer will transform this:

::selection {
    color: white;
    background: black;
}

...(depending on your target browsers/configuration) into something like that:

::-moz-selection {
    color: white;
    background: black;
}

::selection {
    color: white;
    background: black;
}


Mixins work with pseudo element selectors ;) see my mixin:

$prefixes: ("-moz-", "");
@mixin selection($color, $background) {
    @each $prefix in $prefixes {
        ::#{$prefix}selection {
            color: $color;
            background: $background;
        }
    }
}

how to use:

@include selection(white, black);

of course you can make it far more flexible, but it was sufficient for me ;)


While the ::selection pseudo-element was still in the draft spec, text-decoration was not stated as one of the allowed style properties. Given that browsers implement it anyway, they should be following the rules according to that document, disallowing text-decoration as such.

That said, there's nothing wrong with your selector, although it's worth noting that Firefox uses the vendor-prefixed version ::-moz-selection instead. You'd have to repeat the rule to support that browser, along with Chrome, Safari and Opera (see this answer for info).

So in SCSS, you'd do this:

* {
    &::-moz-selection { /* Style any selection */ }
    &::selection { /* Style any selection */ }
}

You might be able to reduce that using mixins, but I'm not sure if mixins work with pseudo-element selectors.


Great mixin, I have changed to work inside a rule by adding "&", it works better for me. I have also added a empty prefix to get the rule with no prefix.

@mixin selection($color, $background) {
   $prefixes: ("-moz-", "-webkit-", "-o-", "-ms-", "");
   @each $prefix in $prefixes {
      &::#{$prefix}selection {
        color: $color;
        background: $background;
      }
   }
}


With compass you could do it like the following:

@import "compass/css3/selection";
@include selection($highlightBackground, $highlightColor)
0

精彩评论

暂无评论...
验证码 换一张
取 消