Как оформить флажок с помощью CSS? - PullRequest
758 голосов
/ 10 ноября 2010

Я пытаюсь оформить флажок, используя следующее:

<input type="checkbox" style="border:2px dotted #00f;display:block;background:#ff0000;" />

Но стиль не применяется.Флажок по-прежнему отображает стиль по умолчанию.Как мне придать ему указанный стиль?

Ответы [ 28 ]

6 голосов
/ 19 апреля 2018

Мое решение

input[type="checkbox"] {
  cursor: pointer;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  outline: 0;
  background: lightgray;
  height: 16px;
  width: 16px;
  border: 1px solid white;
}

input[type="checkbox"]:checked {
  background: #2aa1c0;
}

input[type="checkbox"]:hover {
  filter: brightness(90%);
}

input[type="checkbox"]:disabled {
  background: #e6e6e6;
  opacity: 0.6;
  pointer-events: none;
}

input[type="checkbox"]:after {
  content: '';
  position: relative;
  left: 40%;
  top: 20%;
  width: 15%;
  height: 40%;
  border: solid #fff;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
  display: none;
}

input[type="checkbox"]:checked:after {
  display: block;
}

input[type="checkbox"]:disabled:after {
  border-color: #7b7b7b;
}
<input type="checkbox"><br>
<input type="checkbox" checked><br>
<input type="checkbox" disabled><br>
<input type="checkbox" disabled checked><br>
6 голосов
/ 15 мая 2018

Насколько мне известно, это самый простой способ для создания стиля флажка. Просто добавьте: after и: checked: after css в зависимости от вашего дизайна.

body{
  background: #DDD;
}
span{
  margin-left: 30px;
}
input[type=checkbox] {
    cursor: pointer;
    font-size: 17px;
    visibility: hidden;
    position: absolute;
    top: 0;
    left: 0;
    transform: scale(1.5);
}

input[type=checkbox]:after {
    content: " ";
    background-color: #fff;
    display: inline-block;
    color: #00BFF0;
    width: 14px;
    height: 19px;
    visibility: visible;
    border: 1px solid #FFF;
    padding: 0 3px;
    margin: 2px 0;
    border-radius: 8px;
    box-shadow: 0 0 15px 0 rgba(0,0,0,0.08), 0 0 2px 0 rgba(0,0,0,0.16);
}

input[type=checkbox]:checked:after {
    content: "\2714";
    display: unset;
    font-weight: bold;
}
<input type="checkbox"> <span>Select Text</span>
6 голосов
/ 01 сентября 2014

Вот простое решение CSS без jQuery или javascript

Я использую значки FontAwseome, но вы можете использовать любое изображение

input[type=checkbox] {
  display: inline-block;
  font-family: FontAwesome;
  font-style: normal;
  font-weight: normal;
  line-height: 1;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  visibility: hidden;
  font-size: 14px;
}

input[type=checkbox]:before {
  content: @fa-var-square-o;
  visibility: visible;
  /*font-size: 12px;*/
}

input[type=checkbox]:checked:before {
  content: @fa-var-check-square-o;
}
4 голосов
/ 25 сентября 2013

Хлоп! Все эти обходные пути привели меня к выводу, что флажок HTML вроде бы отстой, если вы хотите его стилизовать.

Как предупреждение, это не реализация CSS. Я просто подумала, что поделюсь тем обходным решением, которое мне пришло на тот случай, если кто-нибудь еще найдет его полезным.


Я использовал элемент HTML5 canvas.

Преимуществом этого является то, что вам не нужно использовать внешние изображения и, возможно, можно сэкономить некоторую полосу пропускания.

Недостатком является то, что если браузер по какой-то причине не может правильно его отрендерить, то здесь нет отступления. Хотя вопрос о том, останется ли это в 2017 году, остается спорным.

Обновление

Я нашел старый код довольно некрасивым, поэтому решил переписать его.

Object.prototype.create = function(args){
    var retobj = Object.create(this);

    retobj.constructor(args || null);

    return retobj;
}

var Checkbox = Object.seal({
    width: 0,
    height: 0,
    state: 0,
    document: null,
    parent: null,
    canvas: null,
    ctx: null,

    /*
     * args:
     * name      default             desc.
     *
     * width     15                  width
     * height    15                  height
     * document  window.document     explicit document reference
     * target    this.document.body  target element to insert checkbox into
     */
    constructor: function(args){
        if(args === null)
            args = {};

        this.width = args.width || 15;
        this.height = args.height || 15;
        this.document = args.document || window.document;
        this.parent = args.target || this.document.body;
        this.canvas = this.document.createElement("canvas");
        this.ctx = this.canvas.getContext('2d');

        this.canvas.width = this.width;
        this.canvas.height = this.height;
        this.canvas.addEventListener("click", this.ev_click(this), false);
        this.parent.appendChild(this.canvas);
        this.draw();
    },

    ev_click: function(self){
        return function(unused){
            self.state = !self.state;
            self.draw();
        }
    },

    draw_rect: function(color, offset){
        this.ctx.fillStyle = color;
        this.ctx.fillRect(offset, offset,
                this.width - offset * 2, this.height - offset * 2);
    },

    draw: function(){
        this.draw_rect("#CCCCCC", 0);
        this.draw_rect("#FFFFFF", 1);

        if(this.is_checked())
            this.draw_rect("#000000", 2);
    },

    is_checked: function(){
        return !!this.state;
    }
});

Вот рабочая демонстрация .

В новой версии используются прототипы и дифференциальное наследование для создания эффективной системы создания флажков. Чтобы создать флажок:

var my_checkbox = Checkbox.create();

Это немедленно добавит флажок в DOM и подключит события. Чтобы узнать, установлен ли флажок:

my_checkbox.is_checked(); // true if checked, else false

Также важно отметить, что я избавился от петли.

Обновление 2

В последнем обновлении я не упомянул о том, что использование canvas имеет больше преимуществ, чем просто установка флажка, который выглядит так, как вы хотите. Вы также можете создать multi-state флажки, если хотите.

Object.prototype.create = function(args){
    var retobj = Object.create(this);

    retobj.constructor(args || null);

    return retobj;
}

Object.prototype.extend = function(newobj){
    var oldobj = Object.create(this);

    for(prop in newobj)
        oldobj[prop] = newobj[prop];

    return Object.seal(oldobj);
}

var Checkbox = Object.seal({
    width: 0,
    height: 0,
    state: 0,
    document: null,
    parent: null,
    canvas: null,
    ctx: null,

    /*
     * args:
     * name      default             desc.
     *
     * width     15                  width
     * height    15                  height
     * document  window.document     explicit document reference
     * target    this.document.body  target element to insert checkbox into
     */
    constructor: function(args){
        if(args === null)
            args = {};

        this.width = args.width || 15;
        this.height = args.height || 15;
        this.document = args.document || window.document;
        this.parent = args.target || this.document.body;
        this.canvas = this.document.createElement("canvas");
        this.ctx = this.canvas.getContext('2d');

        this.canvas.width = this.width;
        this.canvas.height = this.height;
        this.canvas.addEventListener("click", this.ev_click(this), false);
        this.parent.appendChild(this.canvas);
        this.draw();
    },

    ev_click: function(self){
        return function(unused){
            self.state = !self.state;
            self.draw();
        }
    },

    draw_rect: function(color, offsetx, offsety){
        this.ctx.fillStyle = color;
        this.ctx.fillRect(offsetx, offsety,
                this.width - offsetx * 2, this.height - offsety * 2);
    },

    draw: function(){
        this.draw_rect("#CCCCCC", 0, 0);
        this.draw_rect("#FFFFFF", 1, 1);
        this.draw_state();
    },

    draw_state: function(){
        if(this.is_checked())
            this.draw_rect("#000000", 2, 2);
    },

    is_checked: function(){
        return this.state == 1;
    }
});

var Checkbox3 = Checkbox.extend({
    ev_click: function(self){
        return function(unused){
            self.state = (self.state + 1) % 3;
            self.draw();
        }
    },

    draw_state: function(){
        if(this.is_checked())
            this.draw_rect("#000000", 2, 2);

        if(this.is_partial())
            this.draw_rect("#000000", 2, (this.height - 2) / 2);
    },

    is_partial: function(){
        return this.state == 2;
    }
});

Я немного изменил Checkbox, использованный в последнем фрагменте, чтобы он был более универсальным, что позволило "расширить" его с помощью флажка, который имеет 3 состояния. Вот демоверсия . Как видите, он уже обладает большей функциональностью, чем встроенный флажок.

Что нужно учитывать при выборе между JavaScript и CSS.

Старый, плохо спроектированный код

Рабочая демоверсия

Сначала настройте холст

var canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d'),
    checked = 0; // The state of the checkbox
canvas.width = canvas.height = 15; // Set the width and height of the canvas
document.body.appendChild(canvas);
document.body.appendChild(document.createTextNode(' Togglable Option'));

Затем разработайте способ обновления самого холста.

(function loop(){
  // Draws a border
  ctx.fillStyle = '#ccc';
  ctx.fillRect(0,0,15,15);
  ctx.fillStyle = '#fff';
  ctx.fillRect(1,1,13,13);
  // Fills in canvas if checked
  if(checked){
    ctx.fillStyle = '#000';
    ctx.fillRect(2,2,11,11);
  }
  setTimeout(loop,1000/10); // refresh 10 times per second
})();

Последняя часть - сделать его интерактивным. К счастью, все довольно просто:

canvas.onclick = function(){
  checked = !checked;
}

Здесь могут возникнуть проблемы в IE из-за их странной модели обработки событий в javascript.


Надеюсь, это кому-нибудь поможет, оно определенно соответствует моим потребностям.

4 голосов
/ 24 ноября 2012

Я думаю, что самый простой способ сделать это - стилизовать label и сделать checkbox невидимым.

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 */
}

checkbox, даже если он скрыт, все равно будет доступен, и его значение будет отправлено при отправке формы. Для старых браузеров вам, возможно, придется изменить класс label на проверенный с помощью JavaScript, потому что я не думаю, что старые версии IE понимают ::checked на checkbox.

3 голосов
/ 16 августа 2017

Простой и легкий шаблон:

input[type=checkbox] {
  cursor: pointer;
}

input[type=checkbox]:checked:before {
  content: "\2713";
  background: #fffed5;
  text-shadow: 1px 1px 1px rgba(0, 0, 0, .2);
  font-size: 20px;
  text-align: center;
  line-height: 8px;
  display: inline-block;
  width: 13px;
  height: 15px;
  color: #00904f;
  border: 1px solid #cdcdcd;
  border-radius: 4px;
  margin: -3px -3px;
  text-indent: 1px;
}

input[type=checkbox]:before {
  content: "\202A";
  background: #ffffff;
  text-shadow: 1px 1px 1px rgba(0, 0, 0, .2);
  font-size: 20px;
  text-align: center;
  line-height: 8px;
  display: inline-block;
  width: 13px;
  height: 15px;
  color: #00904f;
  border: 1px solid #cdcdcd;
  border-radius: 4px;
  margin: -3px -3px;
  text-indent: 1px;
}
<input type="checkbox" checked="checked">checked1<br>
<input type="checkbox">unchecked2<br>
<input type="checkbox" checked="checked" id="id1">
<label for="id1">checked2+label</label><br>
<label for="id2">unchecked2+label+rtl</label>
<input type="checkbox" id="id2">
<br>

https://jsfiddle.net/rvgccn5b/

3 голосов
/ 16 декабря 2016

Изменить стиль флажка с простым CSS3, не требуя манипуляций с JS и HTML

.form input[type="checkbox"]:before {
  display: inline-block;
  font: normal normal normal 14px/1 FontAwesome;
  font-size: inherit;
  text-rendering: auto;
  -webkit-font-smoothing: antialiased;
  content: "\f096";
  opacity: 1 !important;
  margin-top: -25px;
  appearance: none;
  background: #fff;
}

.form input[type="checkbox"]:checked:before {
  content: "\f046";
}

.form input[type="checkbox"] {
  font-size: 22px;
  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: none;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

<form class="form">
  <input type="checkbox" />
</form>
3 голосов
/ 06 апреля 2016

Не требуется JavaScript или Jquery .

Простой способ изменения стиля флажка.

HTML

<input type="checkbox" id="option" />
<label for="option"> <span></span> Click me </label>

CSS

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;
}

Вот ссылка JsFiddle: https://jsfiddle.net/05y2bge3/

3 голосов
/ 02 июня 2019

С чистым CSS, ничего особенного с: before и: after, без преобразований, вы можете отключить внешний вид по умолчанию и затем стилизовать его с помощью встроенного фонового изображения, как в следующем примере.Это работает в Chrome, Firefox, Safari и теперь 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>
2 голосов
/ 04 сентября 2014

Вот версия только для CSS / HTML, Jquery или Javascript вообще не нужны, Простой и чистый html и действительно простой и короткий css.

вот JSFiddle

http://jsfiddle.net/v71kn3pr/

Вот 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>

Вот 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;
}

Это можно адаптировать, чтобы иметь возможность иметь отдельные радио или флажки, группы флажков итакже группы переключателей.

Этот html / css позволит вам также фиксировать щелчок на ярлыке, поэтому флажок будет отмечен и снят, даже если вы нажмете только на ярлык.

Этот тип переключателей / переключателей отлично работает с любой формой, без проблем.Были также протестированы с использованием php, aspx, javafaces и coldfusion.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...