1

I am currently trying to modify the CSS of a generated HTML page. I do not have access to run scripts on this page or change the base HTML.

The form has inputs and I am trying to create floating labels for them, which I typically do something like this:

<input id="email">
<label for="email">E-mail</label>

With CSS something like this:

input:focus + label { top: 100%; }

However the generated HTML is structured like this, with the label before the input and error blocks between:

<label for="email">Email Address</label>
<div aria-hidden="true" class="error itemLevel">
<p aria-live="polite" role="alert" tabindex="1">Please enter a valid email address.</p>
<input aria-required="true" id="email" title="Email address that can be used to contact you." type="text">

How would I target the label with pure CSS?

Johannes
  • 64,305
  • 18
  • 73
  • 130
  • Are you looking to target previous siblings in pure CSS? This isn't possible - [see this question and associated answers](https://stackoverflow.com/questions/1817792/is-there-a-previous-sibling-css-selector) – PTD Sep 20 '17 at 18:03
  • Thanks, I had seen that question as well as reference to additions to the spec coming that allowed selection of previous siblings. Just didn't know if it had been added yet or scrapped. – Scott Wicken Sep 20 '17 at 18:27

1 Answers1

2

You can use an attribute selector:

label[for="email"] { ... }
Johannes
  • 64,305
  • 18
  • 73
  • 130
  • Awesome, thanks. What if every input is like this with different IDs? – Scott Wicken Sep 20 '17 at 17:59
  • I am not yet sure what you want in the end. They have to have different IDs. Certainly you can address every `for` label individually, or you can simply address *all* labels as `label` – Johannes Sep 20 '17 at 18:14
  • They all were in parent divs, so I ended up actually going with `.parentClass:focus-within label { }` – Scott Wicken Sep 20 '17 at 18:25
  • 1
    Note `focus-with` is not supported by IE or Edge (of course) – sn3ll Sep 20 '17 at 18:28
  • Oh of course, thanks sn3ll. Ironically what I'm doing is Microsoft related :P – Scott Wicken Sep 20 '17 at 18:30
  • @ScottWicken - you should provide your solution as an answer to this question. It will make it easier for people to find who, like me, may not have been aware of the `:focus-within` pseudo-class – PTD Sep 20 '17 at 19:23