Home > Back-end >  Apply styles to parent using sass
Apply styles to parent using sass

Time:12-28

Lets say i have this structure :

<li>Something something  <input type="checkbox"></li>

How could i apply a simple text-decoration: line-through; to li content when checkbox is checked ?

I tried this with no luck using the & sass selector :

li {
 & input:checked {
    text-decoration: line-through;
  }
}

CodePudding user response:

You can't do it. A Element has only access to his child and siblings.

With the siblings there is a neat trick where you can achive a similar result. At first you need to move your checkbox at the beginning (html) so you can style the next siblings with ~ selector.

Then you can apply some css rules to the parent to swap back to order.

div {
  display: flex;
  flex-flow: row-reverse;
}

div input[type="checkbox"]:checked ~ span {
  text-decoration: underline;
}
<div>
  <input type="checkbox">
  <span>Hallo Text</span>
</div>

CodePudding user response:

Sorry but you can´t, you need javascript or SassScript to do that, you can try this https://sass-lang.com/documentation/style-rules/parent-selector

CodePudding user response:

You don't need Javascript for this, but you do need to be able to add something to your HTML.

You can do it if you are able to add an element - put the text into its own div and putting it after the input.

Then use CSS grid on the li element, changing the order that the input and the div are shown. This just changes the visual order so you can still use the sign to indicate the element which is the immediately following sibling of the input.

li {
  display: inline-grid;
  grid-template-columns: auto auto;
}

li input:nth-child(1) {
  order: 2;
}

li div:nth-child(2) {
  order: 1;
}

input:checked div {
  text-decoration: line-through;
}
<ul>
  <li><input id='input' type="checkbox">
    <div>Something something</div>
  </li>
</ul>

  • Related