Why was ::selection removed from the CSS Selectors spec, and how does its specificity work against type selectors?

前端 未结 4 1568
一个人的身影
一个人的身影 2021-02-08 07:06

Some questions about using CSS to specify the color of selected text:

  1. https://developer.mozilla.org/En/CSS/::selection says that,

    :

4条回答
  •  旧巷少年郎
    2021-02-08 07:47

    Type selectors (e.g. body) and pseudo-element selectors (e.g. ::selection) do indeed have the same specificity, but specificity only comes into play when two selectors select the same element.

    The body selector doesn’t select selected text, or any text at all — it selects the element. It’s the element, and not its text, that has the background colour.

    Whereas ::selection selects an imaginary element that surrounds currently selected text on the page. So there’s no conflict between styles set on body and ::selected, because the selectors select different things.

    Example

    Imagine you had the following HTML:

    
        I am some body text.
    
        

    I am some text in a paragraph.

    And the following CSS:

    p {
        background-color: red;
    }
    
    body {
        background-color: white;
    }
    

    Both selectors have the same specificity, but the

    ’s background will still be red, because it’s not the element.

    The same is true if you replace p with ::selection — selected text’s background will be red, because text within the element is not the element.

    So, basically, what you said here:

    body isn't a match for selected body text except when the ::selection pseudo-element is specified as part of the selector

提交回复
热议问题