Search code examples
csscheckboxalignment

How do I center a custom checkbox vertically in div?


I am trying to use flex to align elements vertically, but the custom checkbox is not aligned, the code below shows the problem clearly.Does anyone know what the problem is?

input[type=checkbox] {
  cursor: pointer;
  font-size: 17px;
  visibility: hidden;
  transform: scale(1.2);
}

input[type=checkbox]:after {
  content: " ";
  background-color: #fff;
  display: inline-block;
  color: #00BFF0;
  width: 14px;
  height: 18px;
  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.09), 0 0 5px 0 rgba(0, 0, 0, 0.18);
}

input[type=checkbox]:checked:after {
  content: "\2714";
  display: unset;
  font-weight: bold;
}
<div style="display:inline-block; height:40px; display: flex;  align-items: center; border: 1px solid 
        black;">

  <input type="checkbox">
  <span id="text">TEXTTEXTTEXTTEXT</span>
</div>


Solution

  • Given you are defining the dimensions explicitly, you can set the pseudo element with position:relative; top: -50% .

    For this approach, remember to left-pad the label:

      input[type=checkbox] {
            cursor: pointer;
            font-size: 17px;
            visibility: hidden;
            transform: scale(1.2);
        }
    
        input[type=checkbox]:after {
            content: " ";
            background-color: #fff;
            display: inline-block;
            position:relative;
            top:-50%;
            left:-14px;
            color: #00BFF0;
            width: 14px;
            height: 18px;
            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;
        }
     
        <div style="display:inline-block; height:40px; display: flex;  align-items: center; border: 1px solid black;padding-left: 22px"> 
    
        <input type="checkbox">
        <span id="text">TEXTTEXTTEXTTEXT</span>
        </div>