adamj adamj - 1 month ago 7
CSS Question

CSS update :after when input is checked

Please note the HTML cannot be modified.

HTML:

<div class="form-group newsletter">
<div class="checkbox">
<label><input name="newsletter" type="checkbox" value="Sign me up for exclusive discounts and style advice by email, post and text" aria-invalid="false">Sign me up for exclusive discounts and style advice by email, post and text</label>
</div>
</div>


SASS:

.form-group {
input {
opacity: 0;
}
label {
&:after {
float: left;
display: block;
content: "";
width: 52px; height: 52px;
margin-right: 35px;
background: url('../img/checkbox-default.png') no-repeat;
}
input:checked ~ &:after { // This. Not sure how to make this work
background: url('../img/checkbox-checked.png') no-repeat;
}
}
}


https://jsfiddle.net/dfx78wob/

Answer

I'd put the :after on the input instead, that way to can check whether it is checked or not and change that elements :after

Don't give the input an opacity just hide it behind the new box.

You may need to change the position of the :after now though.

label {
  margin-left: 60px; 
}
input {
  position: relative;
  left: -30px;
}
input:after {
  content: "";
  display: block;
  position: absolute;
  left: -20px;
  width: 52px; height: 52px;
  background: #000000;
}
input:checked:after {
  background: #cdcdcd;
}
<div class="form-group newsletter">
    <div class="checkbox">
        <label><input name="newsletter" type="checkbox" value="Sign me up for exclusive discounts and style advice by email, post and text" aria-invalid="false">Sign me up for exclusive discounts and style advice by email, post and text</label>
    </div>
</div>

For the SASS version something like this will work, I've add [type="checkbox"] as you wouldn't want this on all inputs.

SASS:

label {
  margin-left: 60px; 
}
input[type="checkbox"] {
  position: relative;
  left: -30px;

  &:after {
    content: "";
    display: block;
    position: absolute;
    left: -20px;
    width: 52px; height: 52px;
    background: url('../img/checkbox-default.png') no-repeat;
  }
  &:checked:after {
    background: url('../img/checkbox-checked.png') no-repeat;
  }
}
Comments