Search code examples
htmlcssformscheckbox

Need checkbox with an x in it


I need a form with a bunch of checkboxes which would become a box with x in it if clicked. I have managed to create such a checkbox (it's a custom checkbox), but the x is not coming when I click it. Instead when I try to give a background color if checked, it's working properly. Here is my code

CSS :

.checkbox-row { font-size:6.0pt;line-height:115%;font-family: "Times New Roman",serif;color:#1F1F1F; display:inline-block;

}

 input[type="checkbox"] {
      display: none;
    }

    .custom-checkbox {
      width: 7px;
height:7px;
      border: 0.5px solid #000;
      cursor: pointer;
 font-size: 14px;
    box-sizing: border-box;

display:inline-block;
    }

    input[type="checkbox"]:checked + .custom-checkbox {
     content: 'X' !important;
      font-size: 14px !important;
      color: black;

      text-align: center;
      line-height: 7px;
    }

Here is my HTML code :

<div class="checkbox-row">

                <label>
                    <input type="checkbox" th:checked="${flag}"/> <span class="custom-checkbox"></span>
                    Rural 
                </label>

                <label>
                    <input type="checkbox" th:checked="${customer.getActive()}"/> <span class="custom-checkbox">  </span>
Semi urban
                </label>

                 <label>
                    <input type="checkbox" th:checked="${flag ? false: true}"/> <span class="custom-checkbox">  </span>
 Urban
                </label>

<br>
        
    </div>

Solution

  • The content property – when used on an element – does not work as your code suggests you think it does. Check the MDN docs about the content property for a full explanation. In short, you cannot put text into an element using the content property. You can however put text into a pseudo element using the content property.

    If you change your selector input[type="checkbox"]:checked + .custom-checkbox to input[type="checkbox"]:checked + .custom-checkbox::before you will see the "X" you want to appear. Of course you may need to edit your styling to get it to look right but you'll get your "X".