Estilizar input tipo checkbox com CSS puro

2a atrás

0 0

A esquerda é um checkbox nativo e a direita um checkbox customizado com #CSS

Para começar, adicione no HTML a tag do input checkbox:

<input type="checkbox">

No CSS, vamos redefinir a aparência nativa do input:

input[type='checkbox'] {
  appearance: none;
  height: 1.5em;
  position: relative;
  width: 1.5em;
}

Em seguida vamos criar dois pseudo-elementos utilizando after e before, para a caixa do checkbox e símbolo de checado respectivamente:

input[type='checkbox']::after, input[type='checkbox']::before {
  box-sizing: border-box;
  position: absolute;
}
    
input[type='checkbox']::after {
  border-bottom: 3px solid #FFFFFF;
  border-right: 3px solid #FFFFFF;
  content: '';
  height: 75%;
  left: 50%;
  top: 50%;
  transform: scale(0.1) translate(-50%, -50%);
  transition: transform 0.2s;
  width: 40%;
}
    
input[type='checkbox']::before {
  border: 3px solid #000000;
  border-radius: 0.25em;
  content: '';
  height: 100%;
  transition: background-color 0.2s;
  width: 100%;
}

Por fim, vamos adicionar as modificações de estilo, caso o input esteja checado:

input[type='checkbox']:checked::after {
  transform: rotate(35deg) scale(1) translate(-100%, -30%);
}
    
input[type='checkbox']:checked::before {
  background-color: #000000;
}

O código completo ficará assim:

<!DOCTYPE html>
<html>
<head>
<style>
  input[type='checkbox'] {
    appearance: none;
    height: 1.5em;
    position: relative;
    width: 1.5em;
  }
    
  input[type='checkbox']::after, input[type='checkbox']::before {
    box-sizing: border-box;
    position: absolute;
  }
    
  input[type='checkbox']::after {
    border-bottom: 3px solid #FFFFFF;
    border-right: 3px solid #FFFFFF;
    content: '';
    height: 75%;
    left: 50%;
    top: 50%;
    transform: scale(0.1) translate(-50%, -50%);
    transition: transform 0.2s;
    width: 40%;
  }
    
  input[type='checkbox']::before {
    border: 3px solid #000000;
    border-radius: 0.25em;
    content: '';
    height: 100%;
    transition: background-color 0.2s;
    width: 100%;
  }
    
  input[type='checkbox']:checked::after {
    transform: rotate(35deg) scale(1) translate(-100%, -30%);
  }
    
  input[type='checkbox']:checked::before {
    background-color: #000000;
  }
</style>
</head>
<body>
  <input type="checkbox">
</body>
</html>


Comentários (0)

0/512
Link