Home > Software engineering >  Why use :before and :after instead of styling components directly?
Why use :before and :after instead of styling components directly?

Time:05-04

The company I work for has an in-house extension of bootstrap classes. I'm having difficulty using the checkbox they provide, so I have to dive into their code. I'm starting with this HTML snippet:

<div >                
    <label for="checkbox-id">Some Text</label>
    <input  id="checkbox-id" name="checkbox-name" role="checkbox" type="checkbox" value="y">
</div>

Their checkbox css contains this ("XXX" is in place of a string that would identify the company I work for):

.XXXbs-checkbox input[type=checkbox] {
    opacity: 0;
    margin-left: 4px;
    cursor: pointer;
    z-index: 1;
    width: 100%;
}

Opacity is 0, making the actual checkbox from the above HTML invisible. Meanwhile, they also have this:

.XXXbs-checkbox>label::before {
    font-family: XXX-icon;
    content: "\e903";
    font-size: 32px;
    position: absolute;
    top: -15px;
    left: 0;
}

to place an empty checkbox before the label, and this:

.XXXbs-checkbox>input[type=checkbox]:checked label::before {
    content: "\e904";
    color: #000
}

to render a box with a check mark in it.

My question is, why would you use this approach? Why would you draw a fake checkbox in front of the label instead of just styling the actual checkbox?

CodePudding user response:

Why would you draw a fake checkbox in front of the label instead of just styling the actual checkbox?

Because the amount of styling you can apply to a checkbox itself is very, very limited.

CodePudding user response:

This has been discussed for several years now. You can find a (not only historically) interesting discussion here:

How to style a checkbox using css

  • Related