首页 > 解决方案 > 如何为我的复选框赋予背景颜色?

问题描述

我想为我的复选框赋予背景颜色。这是我的代码

input[type='checkbox'] {
    width: 20px;
    height: 20px;
    background: white;
    border-radius: 5px;
    border: 2px solid red;
    vertical-align: middle;
    margin: 10px;
    cursor: pointer;
}
<div class="card-header">
    <input type="checkbox" class="customCheckBox" name="checkbox">
    <span>data:
        <span class="font-weight-bold">user</span>
    </span>
</div>

但是,复选框没有获得背景颜色。我在哪里做错了?

标签: htmlcss

解决方案


浏览器原生地为许多输入类型提供了一些样式。如果你想覆盖这些,你必须自己重做很多,但这是可行的(并且经常这样做)。您只需要通过以下方式阻止默认外观:

-moz-appearance: none;
-webkit-appearance: none;

现在您可以看到复选框可以有红色背景。但复选标记不再出现。

input[type='checkbox'] {
    -moz-appearance: none;
    -webkit-appearance: none;
    width: 20px;
    height: 20px;
    background: red;
    border-radius: 5px;
    border: 2px solid red;
    vertical-align: middle;
    margin: 10px;
    cursor: pointer;
}
<div class="card-header">
    <input type="checkbox" class="customCheckBox" name="checkbox">
    <span>data:
        <span class="font-weight-bold">user</span>
    </span>
</div>

要添加复选标记,我能想到的最简单的方法是在检查输入时添加一个伪元素:

input[type='checkbox'] {
    -moz-appearance: none;
    -webkit-appearance: none;
    width: 20px;
    height: 20px;
    background: red;
    border-radius: 5px;
    border: 2px solid red;
    vertical-align: middle;
    margin: 10px;
    cursor: pointer;
}
input[type='checkbox']:checked::after {
    content: '✓';
    display: inline-block;
    text-align: center;
    width: 100%;
}
<div class="card-header">
    <input type="checkbox" class="customCheckBox" name="checkbox">
    <span>data:
        <span class="font-weight-bold">user</span>
    </span>
</div>


推荐阅读