8

Custom Website Selection Colors

 3 years ago
source link: https://www.dannyguo.com/blog/custom-website-selection-colors/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Custom Website Selection Colors

June 13, 2018  ·  238 words  ·  ~2 minutes to read

CSS provides an easy way to style the user’s selected or highlighted elements using the ::selection pseudo-element.

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

/* for Firefox */
::-moz-selection {
    color: white;
    background: purple;
}

Try it out:

Note that background is a shorthand for multiple background-* properties, with background-color being the first one.

Also keep in mind that you cannot combine the selectors like this:

::selection, ::-moz-selection {
    color: white;
    background: purple;
}

This will fail because browsers ignore CSS rules that they consider to have invalid selectors. Chrome won’t recognize the prefixed version, and Firefox won’t recognize the unprefixed version, so they both reject the rule.

Browser Support

You should include the -moz- prefixed version for now to support Firefox, but be aware that Firefox won’t need the prefix from version 62 onward.

According to Can I use, about 85% of users are on browsers that support this feature. iOS Safari is the notable holdout.

Specific Styling

The previous example applies the changes to the entire page, but you can also limit them to specific elements using standard selectors.

.iron-man::selection {
    color: #beba46;
    background: #790d0d;
}

.iron-man::-moz-selection {
    color: #beba46;
    background: #790d0d;
}

.incredible-hulk::selection {
    color: #bf80ff;
    background: #70964b;
}

.incredible-hulk::-moz-selection {
    color: #bf80ff;
    background: #70964b;
}

.thor::selection {
    color: #e63900;
    background: #363636;
}

.thor::-moz-selection {
    color: #e63900;
    background: #363636;
}

Try it out:

Continue the discussion on Medium, on Reddit, or in the comments below.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK