Home > database >  CSS style for ::after with plus( ) selector
CSS style for ::after with plus( ) selector

Time:11-12

I want to add some CSS style for ::after when the input is checked.
For example, I want to change the color of 'A' from red to blue.

What I tried:

.container::after {
  content: 'A';
  color: red;
}

.container>input:checked  ::after {
  color: blue;
}
<label class="container">
  <input type="checkbox" />
</label>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

And:

.container::after {
  content: 'A';
  color: red;
}

.container>input:checked .container::after {
  color: blue;
}
<label class="container">
  <input type="checkbox" />
</label>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Any help would be appreciated.
Thanks!

Edit:
I don't want to modify parent style from the child!
::after is inside the parent. Right along the input.
They're siblings.
google chrome inspect

You can set below styles for container and they affects the ::after. because it's INSIDE the container.

.container {
  display: flex;
  justify-content: center;
  align-items: center;
}

CodePudding user response:

This isn't going to be possible in pure CSS.

In the accepted version of this answer I was entirely wrong about the reason for this! I've always assumed that the ::after pseudo-element was placed after the element -- hence, y'know, the name -- but apparently I've been wrong about that for years; the ::before and ::after pseudo-elements are actually first and last children of the main element. Many thanks to @MRNafisiA for pointing this out in comments!

Except not really, because they're still not treated as part of the DOM. Sibling selectors can not be used to match pseudo-elements, and they will not be included in any other selectors that would normally match child elements (first-child, last-child, etc).

So the closest you can get is probably input:checked::after {} (though some extra layout fiddling is necessary to get past the sort-of-zero-width checkbox.)

label {display: block}

input::after {
  content: "A";
  color: red;
  margin-left: 1.2em;
}

input:checked::after {
  color: blue
}
<label><input type="checkbox"></label>
<label><input type="checkbox"></label>
<label><input type="checkbox"></label>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related