Кастомные чекбоксы на CSS
Стандартные чекбоксы часто выглядят скучно и не вписываются в дизайн сайта. С помощью CSS мы можем создать красивые кастомные чекбоксы, которые будут одинаково хорошо выглядеть во всех браузерах. В этой статье мы реализуем чекбокс с анимацией при переключении.
HTML структура
Для создания кастомного чекбокса нам понадобится обернуть input в label и добавить span для визуального представления:
<label class="custom-checkbox">
<input type="checkbox">
<span class="checkbox-icon"></span>
<span class="checkbox-text">Согласен с условиями</span>
</label>
Базовые стили
Сначала скроем стандартный чекбокс с помощью свойства opacity и создадим стили для кастомного:
.custom-checkbox {
display: flex;
align-items: center;
cursor: pointer;
user-select: none;
margin: 10px 0;
}
.custom-checkbox input {
position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;
}
.checkbox-icon {
position: relative;
height: 18px;
width: 18px;
border: 2px solid #ccc;
border-radius: 3px;
margin-right: 10px;
transition: all 0.3s;
}
.checkbox-text {
font-size: 16px;
}
Стили для отмеченного состояния
Добавим стили для отмеченного состояния с помощью псевдокласса :checked и создадим галочку с помощью псевдоэлемента :after:
.custom-checkbox input:checked ~ .checkbox-icon {
background-color: #4CAF50;
border-color: #4CAF50;
}
.checkbox-icon:after {
content: "";
position: absolute;
display: none;
left: 5px;
top: 1px;
width: 4px;
height: 9px;
border: solid white;
border-width: 0 2px 2px 0;
transform: rotate(45deg);
}
.custom-checkbox input:checked ~ .checkbox-icon:after {
display: block;
}
Анимация переключения
Добавим плавную анимацию переключения с помощью свойства transition:
.checkbox-icon {
transition: all 0.2s ease-in-out;
}
Итоговый код
Вот полный код кастомного чекбокса:
<label class="custom-checkbox">
<input type="checkbox">
<span class="checkbox-icon"></span>
<span class="checkbox-text">Согласен с условиями</span>
</label>
.custom-checkbox {
display: flex;
align-items: center;
cursor: pointer;
user-select: none;
margin: 10px 0;
}
.custom-checkbox input {
position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;
}
.checkbox-icon {
position: relative;
height: 18px;
width: 18px;
border: 2px solid #ccc;
border-radius: 3px;
margin-right: 10px;
transition: all 0.2s ease-in-out;
}
.checkbox-text {
font-size: 16px;
}
.custom-checkbox input:checked ~ .checkbox-icon {
background-color: #4CAF50;
border-color: #4CAF50;
}
.checkbox-icon:after {
content: "";
position: absolute;
display: none;
left: 5px;
top: 1px;
width: 4px;
height: 9px;
border: solid white;
border-width: 0 2px 2px 0;
transform: rotate(45deg);
}
.custom-checkbox input:checked ~ .checkbox-icon:after {
display: block;
}
: