Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

Solution 2:

You can do like this, where you add an extra div, absolute positioned, which acts as the border, ... and no script is required.

.login-form-input {
  margin-left: 20px;
  width: 90%;
  outline: none;
}

.login-form-label {
  font-size: 13px;
  font-weight: 300;
  padding-left: 20px;
}

.login-form-field {
  position: relative;
  width: 100%;
  border-radius: 0px;
  height: 6rem;
  box-shadow: 0px0px0px;
}
.login-form-fieldinput ~ .login-form-field-border {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  box-sizing: border-box;  
  border: 0.5px solid grey;
  z-index: -1
}
.login-form-fieldinput:focus ~ .login-form-field-border {
  border: 2px solid blue;  
}
<divclass="login-form-field"><labelfor="email"class="login-form-label">Email:</label><inputclass="login-form-input"autofocus="autofocus"type="email"value=""name="user[email]"id="user_email"><divclass="login-form-field-border"></div></div>

Solution 3:

CSS does not have native support for parent selecting. If your goal is to have .login-form-field have a blue border on focus you're going to have to rely on JavaScript to add the respective CSS.

The following CSS:

.login-form-field.highlight {
  border-color: blue;
}

With the following jQuery

$('.login-form-field').hover(function() {
    $(this).toggleClass('highlight');
});

Would achieve that goal. I should note that jQuery is certainly not necessary here; it's just what I prefer to use.

Solution 4:

Although this is an old answer. I am answering this so anyone who lands here can use just CSS to achieve this.

Use CSS3 pseudo element: focus-within

You could do:

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

Solution 5:

if you want to give the border color when the input is active you can add like this:

.login-form-input:focus {
  border:1px solid blue;
}

Post a Comment for "Css Focus On Child Element Change A Parent Element"