Wondering whether if there is a css-only way to perform to toggle styles on the corresponding label on input\'s focus. So far I have:
$(
There is no selector to match a preceding element... This matches a label immediately followed by an input tag.
input:focus + label {
color: red;
}
If you are willing to switch elements, than here you go
Demo
<div>
<input type="text" />
<label for="e_mail">E-Mail</label>
</div>
label {
float: left;
margin-right: 5px;
}
input[type=text]:focus + label {
color: red;
}
Explanation: We are using +
adjacent selector here, so when the textbox is focused, we select the label
tag and apply color red
Note: Don't forget to clear floats ;)
Try this way:- Place your label after input and float it left. And apply siblings.
<div class="row">
<input id="contact_form_mail" name="contact_form_mail" type="email" placeholder="Your e-mail address...">
<label for="contact_form_mail">Email</label>
</div>
label {
float:left;
}
input:focus + label {
color:red;
}
This is a hack to get the adjacent sibling selector work as it applies only on the following element and not the preceding one. ~
will select all the adjascent siblings after this element. So if you are having different .row
for each section of inputs then use +
.
First we can use a selector that matches a label immediately followed by the input tag (input:focus + label). But there is still the problem, that the label follows after the actual input field. If one would like to have it above the text input we need to switch the positions of the controls. This can be done with a CSS pseudo-table.
<div class="pseudo-table">
<input id="yourname" name="yourname" type="text" placeholder="Name...">
<label for="yourname">Name</label>
</div>
The style for the artifical table is...
.pseudo-table { display: table; }
With this in place we could transform the label e.g. to a table-header-group:
label { display: table-header-group; }
and the input field to a table-row-group:
input { display: table-row-group; }
In combination with our followed by selector we're done and it looks right:
input:focus + label {
color:red;
font-weight: bold;
}
For a demo please see this Fiddle
HTH
This give you label on top of input, highlight label while input focus.
HTML
<div class="row">
<input id="contact_form_mail" name="contact_form_mail" type="email" placeholder="Your e-mail address...">
<label for="contact_form_mail">Email</label>
</div>
<code>
.row{
display:flex;
flex-direction:column-reverse;
align-self:flex-start;
}
.row input:focus{
border: 1px solid red;
}
.row input:focus+label{
color:red;
}
</code>
It's possible with CSS only, without switching the order of the label and input. You can use a :focus-within
CSS pseudo-class on the parent element, which applies to elements, that has a child element with the focus.
In your example, you could use the following:
.row:focus-within label {
color: red;
}
Note, that this pseudo-class is relatively new, so only modern browsers support it.