CSS3 :unchecked pseudo-class

后端 未结 4 838
醉话见心
醉话见心 2020-12-13 03:34

I know there is an official CSS3 :checked pseudo-class, but is there an :unchecked pseudo-class, and do they have the same browser support?

4条回答
  •  温柔的废话
    2020-12-13 04:02

    I think you are trying to over complicate things. A simple solution is to just style your checkbox by default with the unchecked styles and then add the checked state styles.

    input[type="checkbox"] {
      // Unchecked Styles
    }
    input[type="checkbox"]:checked {
      // Checked Styles
    }
    

    I apologize for bringing up an old thread but felt like it could have used a better answer.

    EDIT (3/3/2016):

    W3C Specs state that :not(:checked) as their example for selecting the unchecked state. However, this is explicitly the unchecked state and will only apply those styles to the unchecked state. This is useful for adding styling that is only needed on the unchecked state and would need removed from the checked state if used on the input[type="checkbox"] selector. See example below for clarification.

    input[type="checkbox"] {
      /* Base Styles aka unchecked */
      font-weight: 300; // Will be overwritten by :checked
      font-size: 16px; // Base styling
    }
    input[type="checkbox"]:not(:checked) {
      /* Explicit Unchecked Styles */
      border: 1px solid #FF0000; // Only apply border to unchecked state
    }
    input[type="checkbox"]:checked {
      /* Checked Styles */
      font-weight: 900; // Use a bold font when checked
    }
    

    Without using :not(:checked) in the example above the :checked selector would have needed to use a border: none; to achieve the same affect.

    Use the input[type="checkbox"] for base styling to reduce duplication.

    Use the input[type="checkbox"]:not(:checked) for explicit unchecked styles that you do not want to apply to the checked state.

提交回复
热议问题