How to change the background of a checkbox with CSS only?

1

CSS in width and heigth do not work,

background-color

input{
  width: 20px;
  height: 20px;
}
input:checked{
  background-color: blue;
  width: 25px;
  height: 25px;
}
<input type="checkbox">
    
asked by anonymous 06.08.2018 / 17:44

3 answers

1

As stated by colleagues each user-agente of each browser has its "default style" for some HTML components, among them you can easily repair some inputs as radio , checkbox , select , etc. in FireFox is different from Chrome that is different from Safari etc, As you can see in this image.

InthecaseofCheckboxyoucansolvethisbyremovingallthedefaultpropertiesofuser-agenteusingall:unsetintheelement.

SeeintheelementbelowthatI'vestyledinputcheckboxthewayyouwantedtobyjustclearingthedefaultstyles.

input{
    all: unset;
    border: 1px solid black;
  width: 20px;
  height: 20px;
  display: inline-block;
}
input:checked{
  background-color: blue;
  width: 25px;
  height: 25px;
}
<input type="checkbox" name="" id="">
    
06.08.2018 / 18:22
1

Good friend, some properties are apply to all elements.

For example the CheckBox does not contain the background-color property.

    
06.08.2018 / 17:53
1

Now with CSS3 you can customize a checkbox , but it's worth noting that there is no right way to do it, there are actually several methods, some cross-browser and others not.

Label

The most common method, used in% with known%, is to use frameworks to incorporate label .

<label class="chk">
    <input type="checkbox" name="exemplo" />
    <span></span>
</label>

In this example (default), the input stays within checkbox and checkbox serves as the "anchor" for the style.

Applying CSS, you can already have some results.

.chk input {
    display: none;
}

.chk span {
    width: 12px;
    height: 12px;
    display: block;
    background-color: #fff;
    border: 1px solid #DDD;
}

.chk input:checked + span {
    background-color: #c03;
}
<label class="chk">
    <input type="checkbox" name="exemplo" />
    <span></span>
</label>

You can use images in place of color, the nice thing about using this method is that you can fully control the span

    
06.08.2018 / 18:03