1

I am trying to use a small pseudo element to highlight required inputs.

input:required::before {
  content: "\2022";
  font-size: 32px;
  position: absolute;
  color: orange;
  top: -16px;
  left: -4px;
} 

The css above will not work, because inputs can't have pseudo elements. I have to put the pseudo elements on a wrapper.

.input-wrapper::before {
  ...
} 

But then the pseudo class :required is not accessible. Is there anyway to achieve pseudo elements on inputs by their pseudo class with pure css? I.e. how to best create pseudo elements on non-container tags by that elements pseudo class?

blid
  • 971
  • 13
  • 22
  • 3
    You may add a `span` element after `input` and style it i.e `input:required + span { ... }`. – Mohammad Usman Jan 10 '18 at 08:10
  • I'd recommend wrapping the input as you specified, then using JS to connect the 2, so if input is required then add .required class to the input wrapper... this could seem a little more complicated than necessary though. – mattroberts33 Jan 10 '18 at 08:13
  • Possible duplicate of [Can I use a :before or :after pseudo-element on an input field?](https://stackoverflow.com/questions/2587669/can-i-use-a-before-or-after-pseudo-element-on-an-input-field) – Mohammad Usman Jan 10 '18 at 08:14
  • I forgot about adjacent selectors, Mohammad's comment will do the trick - that will target a span so long as it is directly following an input:required – mattroberts33 Jan 10 '18 at 08:21
  • Thank you Mohammad, it works. Is it impossible to do this with a wrapper? Maybe the brewing :has() selector could achieve that. – blid Jan 10 '18 at 08:37
  • It could, with `.input-wrapper:has(> :required)::before`, but there no plans to bring :has() into CSS even if it does enter the Selectors standard, so it might as well not exist :/ – BoltClock Jan 10 '18 at 08:39

1 Answers1

0

You could wrap the input in a label and then use ::after on that.

Like this:

.required {
  display: flex;
}

.required::after {
  content: '';
  display: block;
  width: 20px;
  height: 20px;
  background: red;
}
<label class="required">Label text
  <input required type="text"/>
</label>
VilleKoo
  • 2,827
  • 2
  • 14
  • 23