How to style a checkbox using CSS

前端 未结 30 3514
日久生厌
日久生厌 2020-11-21 04:26

I am trying to style a checkbox using the following:

相关标签:
30条回答
  • 2020-11-21 05:21

    2020 solution - pure CSS checkboxes and radio buttons with no external dependencies

    I have been scrolling and scrolling and tons of these answers simply throw accessibility out the door and violate WCAG in more than one way. I threw in radio buttons since most of the time when you're using custom checkboxes you want custom radio buttons too.

    Fiddles:

    • Checkboxes - pure CSS - free from 3rd party libraries
    • Radio buttons - pure CSS - free from 3rd party libraries
    • Checkboxes* that use FontAwesome but could be swapped with Glyphicons, etc. easily

    Late to the party but somehow this is still difficult in 2019 2020 so I have added my three solutions which are accessible and easy to drop in.

    These are all JavaScript free, external library free*, and accessible...

    If you want to plug-n-play with any of these just copy the style sheet from the fiddles, edit the color codes in the CSS to fit your needs, and be on your way. You can add a custom svg checkmark icon if you want for the checkboxes. I've added lots of comments for those non-CSS'y folks.

    If you have long text or a small container and are encountering text wrapping underneath the checkbox or radio button input then just convert to divs like this.

    Longer explanation: I needed a solution that does not violate WCAG, doesn't rely on JavaScript or external libraries, and that does not break keyboard navigation like tabbing or spacebar to select, that allows focus events, a solution that allows for disabled checkboxes that are both checked and unchecked, and finally a solution where I can customize the look of the checkbox however I want with different background-color's, border-radius, svg backgrounds, etc.

    I used some combination of this answer from @Jan Turoň to come up with my own solution which seems to work quite well. I've done a radio button fiddle that uses a lot of the same code from the checkboxes in order to make this work with radio buttons too.

    I am still learning accessibility so if I missed something please drop a comment and I will try to correct it here is a code example of my checkboxes:

    input[type="checkbox"] {
      position: absolute;
      opacity: 0;
      z-index: -1;
    }
    
    /* Text color for the label */
    input[type="checkbox"]+span {
      cursor: pointer;
      font: 16px sans-serif;
      color: black;
    }
    
    /* Checkbox un-checked style */
    input[type="checkbox"]+span:before {
      content: '';
      border: 1px solid grey;
      border-radius: 3px;
      display: inline-block;
      width: 16px;
      height: 16px;
      margin-right: 0.5em;
      margin-top: 0.5em;
      vertical-align: -2px;
    }
    
    /* Checked checkbox style (in this case the background is green #e7ffba, change this to change the color) */
    input[type="checkbox"]:checked+span:before {
      /* NOTE: Replace the url with a path to an SVG of a checkmark to get a checkmark icon */
      background-image: url('https://cdnjs.cloudflare.com/ajax/libs/ionicons/4.5.6/collection/build/ionicons/svg/ios-checkmark.svg');
      background-repeat: no-repeat;
      background-position: center;
      /* The size of the checkmark icon, you may/may not need this */
      background-size: 25px;
      border-radius: 2px;
      background-color: #e7ffba;
      color: white;
    }
    
    /* Adding a dotted border around the active tabbed-into checkbox */
    input[type="checkbox"]:focus+span:before,
    input[type="checkbox"]:not(:disabled)+span:hover:before {
      /* Visible in the full-color space */
      box-shadow: 0px 0px 0px 2px rgba(0, 150, 255, 1);
    
      /* Visible in Windows high-contrast themes
         box-shadow will be hidden in these modes and
         transparency will not be hidden in high-contrast
         thus box-shadow will not show but the outline will
         providing accessibility */
      outline-color: transparent; /*switch to transparent*/
      outline-width: 2px;
      outline-style: dotted;
      }
    
    
    /* Disabled checkbox styles */
    input[type="checkbox"]:disabled+span {
      cursor: default;
      color: black;
      opacity: 0.5;
    }
    
    /* Styles specific to this fiddle that you do not need */
    body {
      padding: 1em;
    }
    h1 {
      font-size: 18px;
    }
    <h1>
      NOTE: Replace the url for the background-image in CSS with a path to an SVG in your solution or CDN. This one was found from a quick google search for a checkmark icon cdn
    </h1>
    
    <p>You can easily change the background color, checkbox symbol, border-radius, etc.</p>
    
    <label>
      <input type="checkbox">
      <span>Try using tab and space</span>
    </label>
    
    <br>
    
    <label>
      <input type="checkbox" checked disabled>
      <span>Disabled Checked Checkbox</span>
    </label>
    
    <br>
    
    <label>
      <input type="checkbox" disabled>
      <span>Disabled Checkbox</span>
    </label>
    <br>
    
    <label>
      <input type="checkbox">
      <span>Normal Checkbox</span>
    </label>
    
    <br>
    
    <label>
      <input type="checkbox">
      <span>Another Normal Checkbox</span>
    </label>

    0 讨论(0)
  • 2020-11-21 05:21

    It seems you can change the colour of the checkbox in grayscale by using CSS only.

    The following converts the checkboxes from black to gray (which was about what I wanted):

    input[type="checkbox"] {
        opacity: .5;
    }
    
    0 讨论(0)
  • 2020-11-21 05:22

    Simple to implement and easily customizable solution

    After a lot of search and testing I got this solution which is simple to implement and easier to customize. In this solution:

    1. You don't need external libraries and files
    2. You don't need to add extra HTML in your page
    3. You don't need to change checkbox names and id

    Simple put the flowing CSS at the top of your page and all checkboxes style will change like this:

    input[type=checkbox] {
      transform: scale(1.5);
    }
    
    input[type=checkbox] {
      width: 30px;
      height: 30px;
      margin-right: 8px;
      cursor: pointer;
      font-size: 17px;
      visibility: hidden;
    }
    
    input[type=checkbox]:after {
      content: " ";
      background-color: #fff;
      display: inline-block;
      margin-left: 10px;
      padding-bottom: 5px;
      color: #00BFF0;
      width: 22px;
      height: 25px;
      visibility: visible;
      border: 1px solid #00BFF0;
      padding-left: 3px;
      border-radius: 5px;
    }
    
    input[type=checkbox]:checked:after {
      content: "\2714";
      padding: -5px;
      font-weight: bold;
    }
    <input type="checkbox" id="checkbox1" />
    <label for="checkbox1">Checkbox</label>

    0 讨论(0)
  • 2020-11-21 05:22

    Here is a CSS/HTML-only version, no jQuery or JavaScript needed at all, Simple and clean HTML and really simple and short CSS.

    Here is the JSFiddle

    http://jsfiddle.net/v71kn3pr/

    Here is the HTML:

    <div id="myContainer">
        <input type="checkbox" name="myCheckbox" id="myCheckbox_01_item" value="red" />
        <label for="myCheckbox_01_item" class="box"></label>
        <label for="myCheckbox_01_item" class="text">I accept the Terms of Use.</label>
    </div>
    

    Here is the CSS

    #myContainer {
        outline: black dashed 1px;
        width: 200px;
    }
    #myContainer input[type="checkbox"][name="myCheckbox"] {
        display: none;
    }
    #myContainer input[type="checkbox"][name="myCheckbox"]:not(:checked) + label.box {
        display: inline-block;
        width: 25px;
        height: 25px;
        border: black solid 1px;
        background: #FFF ;
        margin: 5px 5px;
    }
    #myContainer input[type="checkbox"][name="myCheckbox"]:checked + label.box {
        display: inline-block;
        width: 25px;
        height: 25px;
        border: black solid 1px;
        background: #F00;
        margin: 5px 5px;
    }
    #myContainer input[type="checkbox"][name="myCheckbox"] + label + label.text {
        font: normal 12px arial;
        display: inline-block;
        line-height: 27px;
        vertical-align: top;
        margin: 5px 0px;
    }
    

    This can be adapted to be able to have individual radio or checkboxes, grooups of checkboxes and groups of radio buttons as well.

    This html/css, will allow you to also capture click on the label, so the checkbox will be checked and unchecked even if you click just on the label.

    This type of checkbox/radio button works perfectly with any form, no problem at all. Have been tested using PHP, ASP.NET (.aspx), JavaServer Faces, and ColdFusion too.

    0 讨论(0)
  • 2020-11-21 05:23

    I'd follow the advice of SW4's answer – to hide the checkbox and to cover it with a custom span, suggesting this HTML:

    <label>
      <input type="checkbox">
      <span>send newsletter</span>
    </label>
    

    The wrap in label neatly allows clicking the text without the need of "for-id" attribute linking. However,

    Do not hide it using visibility: hidden or display: none

    It works by clicking or tapping, but that is a lame way to use checkboxes. Some people still use much more effective Tab to move focus, Space to activate, and hiding with that method disables it. If the form is long, one will save someone's wrists to use tabindex or accesskey attributes. And if you observe the system checkbox behavior, there is a decent shadow on hover. The well styled checkbox should follow this behavior.

    cobberboy's answer recommends Font Awesome which is usually better than bitmap since fonts are scalable vectors. Working with the HTML above, I'd suggest these CSS rules:

    1. Hide checkboxes

       input[type="checkbox"] {
         position: absolute;
         opacity: 0;
         z-index: -1;
       }
      

      I use just negative z-index since my example uses big enough checkbox skin to cover it fully. I don't recommend left: -999px since it is not reusable in every layout. Bushan wagh's answer provides a bulletproof way to hide it and convince the browser to use tabindex, so it is a good alternative. Anyway, both is just a hack. The proper way today is appearance: none, see Joost's answer:

       input[type="checkbox"] {
         appearance: none;
         -webkit-appearance: none;
         -moz-appearance: none;
       }
      
    2. Style checkbox label

       input[type="checkbox"] + span {
         font: 16pt sans-serif;
         color: #000;
       }
      
    3. Add checkbox skin

       input[type="checkbox"] + span:before {
         font: 16pt FontAwesome;
         content: '\00f096';
         display: inline-block;
         width: 16pt;
         padding: 2px 0 0 3px;
         margin-right: 0.5em;
       }
      

    \00f096 is Font Awesome's square-o, padding is adjusted to provide even dotted outline on focus (see below).

    1. Add checkbox checked skin

       input[type="checkbox"]:checked + span:before {
         content: '\00f046';
       }
      

    \00f046 is Font Awesome's check-square-o, which is not the same width as square-o, which is the reason for the width style above.

    1. Add focus outline

       input[type="checkbox"]:focus + span:before {
         outline: 1px dotted #aaa;
       }
      

      Safari doesn't provide this feature (see @Jason Sankey's comment), see this answer for Safari-only CSS

    2. Set gray color for disabled checkbox

       input[type="checkbox"]:disabled + span {
         color: #999;
       }
      
    3. Set hover shadow on non-disabled checkbox

       input[type="checkbox"]:not(:disabled) + span:hover:before {
         text-shadow: 0 1px 2px #77F;
       }
      

    Test it on JS Fiddle

    Try to hover the mouse over the checkboxes and use Tab and Shift+Tab to move and Space to toggle.

    0 讨论(0)
  • 2020-11-21 05:23

    You can avoid adding extra markup. This works everywhere except IE for Desktop (but works in IE for Windows Phone and Microsoft Edge) via setting CSS appearance:

    input[type="checkbox"] {
      -webkit-appearance: none;
      -moz-appearance: none;
      appearance: none;
    
      /* Styling checkbox */
      width: 16px;
      height: 16px;
      background-color: red;
    }
    
    input[type="checkbox"]:checked {
      background-color: green;
    }
    <input type="checkbox" />

    0 讨论(0)
提交回复
热议问题