Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS focus on child element change a parent element

I want to style a form that has the label and input inside the form field and when I'll write something inside the input (probably with focus), I want the borders to light up with some blue. Now I have something like this:

HTML

<div class="login-form-field">
  <label for="email" class="login-form-label">Email:</label>
  <input class="login-form-input" autofocus="autofocus" type="email" value="" name="user[email]" id="user_email">
</div>

CSS

.login-form-input{
  margin-left: 20px;
  width: 90%;
  outline: none;
  border: none;
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  box-shadow: 0 0 0px 1000px white inset;
}
.login-form-label {
  font-size: 13px;
  font-weight: 300;
  padding-left: 20px;
}
.login-form-field{
  width: 100%;
  border-radius: 0px;
  height: 6rem;
  border: 0.5px solid grey;
  box-shadow: 0px 0px 0px;
}

I already tried to select the parent to made some change and other stuff I found on google. The closest I got was to highlight with blue when the mouser was over it with :hover, but i need the color to stay as I'm with the input selected.

.login-form-field:hover {
  border-color: blue !important;
}

Here is the JSFiddle, if anyone could help I would be grateful!

like image 491
Pedro Vieira Avatar asked Dec 15 '22 04:12

Pedro Vieira


1 Answers

You can now do this in pure CSS so no JavaScript is needed.

The new CSS pseudo-class :focus-within would help for cases like this and will help with accessibility when people use tabbing for navigating, common when using screen readers.

.login-form-field:focus-within {
  border-color: blue !important;
}

The :focus-within pseudo-class matches elements that either themselves match :focus or that have descendants which match :focus.

You can check which browsers support this http://caniuse.com/#search=focus-within

like image 172
J J B Avatar answered Dec 16 '22 17:12

J J B