How to style a checkbox using CSS

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

I am trying to style a checkbox using the following:

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

    With pure CSS, nothing fancy with :before and :after, no transforms, you can turn off the default appearance and then style it with an inline background image like the following example. This works in Chrome, Firefox, Safari, and now Edge (Chromium Edge).

    INPUT[type=checkbox]:focus
    {
        outline: 1px solid rgba(0, 0, 0, 0.2);
    }
    
    INPUT[type=checkbox]
    {
        background-color: #DDD;
        border-radius: 2px;
        appearance: none;
        -webkit-appearance: none;
        -moz-appearance: none;
        width: 17px;
        height: 17px;
        cursor: pointer;
        position: relative;
        top: 5px;
    }
    
    INPUT[type=checkbox]:checked
    {
        background-color: #409fd6;
        background: #409fd6 url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==") 3px 3px no-repeat;
    }
    <form>
      <label><input type="checkbox">I Agree To Terms &amp; Conditions</label>
    </form>

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

    Since browsers like Edge and Firefox do not support :before :after on checkbox input tags, here is an alternative purely with HTML and CSS. Of course you should edit CSS according to your requirements.

    Make the HTML for checkbox like this:

    <div class='custom-checkbox'>
        <input type='checkbox' />
        <label>
            <span></span>
            Checkbox label
        </label>
    </div>
    

    Apply this style for the checkbox to change the color label

    <style>
        .custom-checkbox {
            position: relative;
        }
        .custom-checkbox input{
            position: absolute;
            left: 0;
            top: 0;
            height:15px;
            width: 50px;    /* Expand the checkbox so that it covers */
            z-index : 1;    /* the label and span, increase z-index to bring it over */
            opacity: 0;     /* the label and set opacity to 0 to hide it. */
        }
        .custom-checkbox input+label {
            position: relative;
            left: 0;
            top: 0;
            padding-left: 25px;
            color: black;
        }
        .custom-checkbox input+label span {
            position: absolute;  /* a small box to display as checkbox */
            left: 0;
            top: 0;
            height: 15px;
            width: 15px;
            border-radius: 2px;
            border: 1px solid black;
            background-color: white;
        }
        .custom-checkbox input:checked+label { /* change label color when checked */
            color: orange;
        }
        .custom-checkbox input:checked+label span{ /* change span box color when checked */
            background-color: orange;
            border: 1px solid orange;
        }
    </style>
    
    0 讨论(0)
  • 2020-11-21 05:11

    Here is an example, with theme support. It is a modern approach with CSS transitions. There is absolutely no JavaScript required.

    I derived the following code linked in this comment; on a related question.

    Edit: I added radio buttons, as maxshuty suggests.

    const selector = '.grid-container > .grid-row > .grid-col[data-theme="retro"]';
    const main = () => {
      new CheckboxStyler().run(selector);
      new RadioStyler().run(selector);
    };
    
    /*
     * This is only used to add the wrapper class and checkmark span to an existing DOM,
     * to make this CSS work.
     */
    class AbstractInputStyler {
      constructor(options) {
        this.opts = options;
      }
      run(parentSelector) {
        let wrapperClass = this.opts.wrapperClass;
        let parent = document.querySelector(parentSelector) || document.getElementsByTagName('body')[0];
        let labels = parent.querySelectorAll('label');
        if (labels.length) labels.forEach(label => {
          if (label.querySelector(`input[type="${this.opts._inputType}"]`)) {
            if (!label.classList.contains(wrapperClass)) {
              label.classList.add(wrapperClass);
              label.appendChild(this.__createDefaultNode());
            }
          }
        });
        return this;
      }
      /* @protected */
      __createDefaultNode() {
        let checkmark = document.createElement('span');
        checkmark.className = this.opts._activeClass;
        return checkmark;
      }
    }
    
    class CheckboxStyler extends AbstractInputStyler {
      constructor(options) {
        super(Object.assign({
          _inputType: 'checkbox',
          _activeClass: 'checkmark'
        }, CheckboxStyler.defaultOptions, options));
      }
    }
    CheckboxStyler.defaultOptions = {
      wrapperClass: 'checkbox-wrapper'
    };
    
    class RadioStyler extends AbstractInputStyler {
      constructor(options) {
        super(Object.assign({
          _inputType: 'radio',
          _activeClass: 'pip'
        }, RadioStyler.defaultOptions, options));
      }
    }
    RadioStyler.defaultOptions = {
      wrapperClass: 'radio-wrapper'
    };
    
    main();
    /* Theming */
    
    :root {
      --background-color: #FFF;
      --font-color: #000;
      --checkbox-default-background: #EEE;
      --checkbox-hover-background: #CCC;
      --checkbox-disabled-background: #AAA;
      --checkbox-selected-background: #1A74BA;
      --checkbox-selected-disabled-background: #6694B7;
      --checkbox-checkmark-color: #FFF;
      --checkbox-checkmark-disabled-color: #DDD;
    }
    
    [data-theme="dark"] {
      --background-color: #111;
      --font-color: #EEE;
      --checkbox-default-background: #222;
      --checkbox-hover-background: #444;
      --checkbox-disabled-background: #555;
      --checkbox-selected-background: #2196F3;
      --checkbox-selected-disabled-background: #125487;
      --checkbox-checkmark-color: #EEE;
      --checkbox-checkmark-disabled-color: #999;
    }
    
    [data-theme="retro"] {
      --background-color: #FFA;
      --font-color: #000;
      --checkbox-default-background: #EEE;
      --checkbox-hover-background: #FFF;
      --checkbox-disabled-background: #BBB;
      --checkbox-selected-background: #EEE;
      --checkbox-selected-disabled-background: #BBB;
      --checkbox-checkmark-color: #F44;
      --checkbox-checkmark-disabled-color: #D00;
    }
    
    
    /* General styles */
    
    html {
      width: 100%;
      height: 100%;
    }
    
    body {
      /*background: var(--background-color); -- For demo, moved to column. */
      /*color:      var(--font-color);       -- For demo, moved to column. */
      background: #777;
      width: calc(100% - 0.5em);
      height: calc(100% - 0.5em);
      padding: 0.25em;
    }
    
    h1 {
      font-size: 1.33em !important;
    }
    
    h2 {
      font-size: 1.15em !important;
      margin-top: 1em;
    }
    
    
    /* Grid style - using flex */
    
    .grid-container {
      display: flex;
      height: 100%;
      flex-direction: column;
      flex: 1;
    }
    
    .grid-row {
      display: flex;
      flex-direction: row;
      flex: 1;
      margin: 0.25em 0;
    }
    
    .grid-col {
      display: flex;
      flex-direction: column;
      height: 100%;
      padding: 0 1em;
      flex: 1;
      margin: 0 0.25em;
      /* If not demo, remove and uncomment the body color rules */
      background: var(--background-color);
      color: var(--font-color);
    }
    
    .grid-cell {
      width: 100%;
      height: 100%;
    }
    
    
    /* The checkbox wrapper */
    
    .checkbox-wrapper,
    .radio-wrapper {
      display: block;
      position: relative;
      padding-left: 1.5em;
      margin-bottom: 0.5em;
      cursor: pointer;
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;
    }
    
    
    /* Hide the browser's default checkbox and radio buttons */
    
    .checkbox-wrapper input[type="checkbox"] {
      position: absolute;
      opacity: 0;
      cursor: pointer;
      height: 0;
      width: 0;
    }
    
    .radio-wrapper input[type="radio"] {
      position: absolute;
      opacity: 0;
      cursor: pointer;
      height: 0;
      width: 0;
    }
    
    
    /* Create a custom checkbox */
    
    .checkbox-wrapper .checkmark {
      position: absolute;
      top: 0;
      left: 0;
      height: 1em;
      width: 1em;
      background-color: var(--checkbox-default-background);
      transition: all 0.2s ease-in;
    }
    
    .radio-wrapper .pip {
      position: absolute;
      top: 0;
      left: 0;
      height: 1em;
      width: 1em;
      border-radius: 50%;
      background-color: var(--checkbox-default-background);
      transition: all 0.2s ease-in;
    }
    
    
    /* Disabled style */
    
    .checkbox-wrapper input[type="checkbox"]:disabled~.checkmark,
    .radio-wrapper input[type="radio"]:disabled~.pip {
      cursor: not-allowed;
      background-color: var(--checkbox-disabled-background);
      color: var(--checkbox-checkmark-disabled-color);
    }
    
    .checkbox-wrapper input[type="checkbox"]:disabled~.checkmark:after,
    .radio-wrapper input[type="radio"]:disabled~.pip:after {
      color: var(--checkbox-checkmark-disabled-color);
    }
    
    .checkbox-wrapper input[type="checkbox"]:disabled:checked~.checkmark,
    .radio-wrapper input[type="radio"]:disabled:checked~.pip {
      background-color: var(--checkbox-selected-disabled-background);
    }
    
    
    /* On mouse-over, add a grey background color */
    
    .checkbox-wrapper:hover input[type="checkbox"]:not(:disabled):not(:checked)~.checkmark,
    .radio-wrapper:hover input[type="radio"]:not(:disabled):not(:checked)~.pip {
      background-color: var(--checkbox-hover-background);
    }
    
    
    /* When the checkbox is checked, add a blue background */
    
    .checkbox-wrapper input[type="checkbox"]:checked~.checkmark,
    .radio-wrapper input[type="radio"]:checked~.pip {
      background-color: var(--checkbox-selected-background);
    }
    
    
    /* Create the checkmark/indicator (hidden when not checked) */
    
    .checkbox-wrapper .checkmark:after {
      display: none;
      width: 100%;
      position: absolute;
      text-align: center;
      content: "\2713";
      color: var(--checkbox-checkmark-color);
      line-height: 1.1em;
    }
    
    .radio-wrapper .pip:after {
      display: none;
      width: 100%;
      position: absolute;
      text-align: center;
      content: "\2022";
      color: var(--checkbox-checkmark-color);
      font-size: 1.5em;
      top: -0.2em;
    }
    
    
    /* Show the checkmark when checked */
    
    .checkbox-wrapper input[type="checkbox"]:checked~.checkmark:after {
      display: block;
      line-height: 1.1em;
    }
    
    .radio-wrapper input[type="radio"]:checked~.pip:after {
      display: block;
      line-height: 1.1em;
    }
    <link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css" rel="stylesheet" />
    <div class="grid-container">
      <div class="grid-row">
        <div class="grid-col">
          <div class="grid-cell">
            <h1>Pure CSS</h1>
            <h2>Checkbox</h2>
            <label class="checkbox-wrapper">One
              <input type="checkbox" checked="checked">
              <span class="checkmark"></span>
            </label>
            <label class="checkbox-wrapper">Two
              <input type="checkbox">
              <span class="checkmark"></span>
            </label>
            <label class="checkbox-wrapper">Three
              <input type="checkbox" checked disabled>
              <span class="checkmark"></span>
            </label>
            <label class="checkbox-wrapper">Four
              <input type="checkbox" disabled>
              <span class="checkmark"></span>
            </label>
            <h2>Radio</h2>
            <label class="radio-wrapper">One
              <input type="radio" name="group-x">
              <span class="pip"></span>
            </label>
            <label class="radio-wrapper">Two
              <input type="radio" name="group-x">
              <span class="pip"></span>
            </label>
            <label class="radio-wrapper">Three
              <input type="radio" name="group-x" checked disabled>
              <span class="pip"></span>
            </label>
            <label class="radio-wrapper">Four
              <input type="radio" name="group-x" disabled>
              <span class="pip"></span>
            </label>
          </div>
        </div>
        <div class="grid-col" data-theme="dark">
          <div class="grid-cell">
            <h1>Pure CSS</h1>
            <h2>Checkbox</h2>
            <label class="checkbox-wrapper">One
              <input type="checkbox" checked="checked">
              <span class="checkmark"></span>
            </label>
            <label class="checkbox-wrapper">Two
              <input type="checkbox">
              <span class="checkmark"></span>
            </label>
            <label class="checkbox-wrapper">Three
              <input type="checkbox" checked disabled>
              <span class="checkmark"></span>
            </label>
            <label class="checkbox-wrapper">Four
              <input type="checkbox" disabled>
              <span class="checkmark"></span>
            </label>
            <h2>Radio</h2>
            <label class="radio-wrapper">One
              <input type="radio" name="group-y">
              <span class="pip"></span>
            </label>
            <label class="radio-wrapper">Two
              <input type="radio" name="group-y">
              <span class="pip"></span>
            </label>
            <label class="radio-wrapper">Three
              <input type="radio" name="group-y" checked disabled>
              <span class="pip"></span>
            </label>
            <label class="radio-wrapper">Four
              <input type="radio" name="group-y" disabled>
              <span class="pip"></span>
            </label>
          </div>
        </div>
        <div class="grid-col" data-theme="retro">
          <div class="grid-cell">
            <h1>JS + CSS</h1>
            <h2>Checkbox</h2>
            <label>One   <input type="checkbox" checked="checked"></label>
            <label>Two   <input type="checkbox"></label>
            <label>Three <input type="checkbox" checked disabled></label>
            <label>Four  <input type="checkbox" disabled></label>
            <h2>Radio</h2>
            <label>One   <input type="radio" name="group-z" checked="checked"></label>
            <label>Two   <input type="radio" name="group-z"></label>
            <label>Three <input type="radio" name="group-z" checked disabled></label>
            <label>Four  <input type="radio" name="group-z" disabled></label>
          </div>
        </div>
      </div>
    </div>

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

    I prefer to use icon fonts (such as FontAwesome) since it's easy to modify their colours with CSS, and they scale really well on high pixel-density devices. So here's another pure CSS variant, using similar techniques to those above.

    (Below is a static image so you can visualize the result; see the JSFiddle for an interactive version.)

    Checkbox example

    As with other solutions, it uses the label element. An adjacent span holds our checkbox character.

    span.bigcheck-target {
      font-family: FontAwesome; /* Use an icon font for the checkbox */
    }
    
    input[type='checkbox'].bigcheck {
      position: relative;
      left: -999em; /* Hide the real checkbox */
    }
    
    input[type='checkbox'].bigcheck + span.bigcheck-target:after {
      content: "\f096"; /* In fontawesome, is an open square (fa-square-o) */
    }
    
    input[type='checkbox'].bigcheck:checked + span.bigcheck-target:after {
      content: "\f046"; /* fontawesome checked box (fa-check-square-o) */
    }
    
    /* ==== Optional - colors and padding to make it look nice === */
    body {
      background-color: #2C3E50;
      color: #D35400;
      font-family: sans-serif;
      font-weight: 500;
      font-size: 4em; /* Set this to whatever size you want */
    }
    
    span.bigcheck {
      display: block;
      padding: 0.5em;
    }
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
    
    <span class="bigcheck">
      <label class="bigcheck">
        Cheese
        <input type="checkbox" class="bigcheck" name="cheese" value="yes" />
        <span class="bigcheck-target"></span>
      </label>
    </span>

    Here's the JSFiddle for it.

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

    I think the easiest way to do it is by styling a label and making the checkbox invisible.

    HTML

    <input type="checkbox" id="first" />
    <label for="first">&nbsp;</label>
    

    CSS

    checkbox {
      display: none;
    }
    
    checkbox + label {
      /* Style for checkbox normal */
      width: 16px;
      height: 16px;
    }
    
    checkbox::checked + label,
    label.checked {
      /* Style for checkbox checked */
    }
    

    The checkbox, even though it is hidden, will still be accessible, and its value will be sent when a form is submitted. For old browsers you might have to change the class of the label to checked using JavaScript because I don't think old versions of Internet Explorer understand ::checked on the checkbox.

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

    No JavaScript or jQuery required.

    Change your checkbox style simple way.

    input[type="checkbox"] {
      display: none;
      border: none !important;
      box-shadow: none !important;
    }
    
    input[type="checkbox"] + label span {
      background: url(http://imgh.us/uncheck.png);
      width: 49px;
      height: 49px;
      display: inline-block;
      vertical-align: middle;
    }
    
    input[type="checkbox"]:checked + label span {
      background: url(http://imgh.us/check_2.png);
      width: 49px;
      height: 49px;
      vertical-align: middle;
    }
    <input type="checkbox" id="option" />
    <label for="option"> <span></span> Click me </label>

    Here is JsFiddle link

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