0

I'm trying to add the same style to the .block when the input is focused as when it is hovered. What is the best way to add a style to a parent of an input when it is focused? Is there a CSS only solution or will JavaScript be required? If so a jQuery solution is acceptable.

body {
  padding: 1rem 2rem;
}
input {
  background: transparent;
  padding: 1rem;
  outline: none;
  border: none;
  flex: 1;
}
input:hover {
  border-color: red;
}
input:focus ~ .label,
input:not(:focus):valid ~ .label {
  color: #868ca0;
  font-weight: 700;
  border-color: red;
  top: -0.6rem;
  /*padding: 0 0.5rem;*/
  font-size: 14px;
  background: #fff;
  opacity: 1;
}
.label {
  position: absolute;
  left: 1rem;
  top: 1.2rem;
  pointer-events: none;
  color: #666;
  transition: 0.2s ease all;
}
.block {
  padding-right: 1rem;
  width: 300px;
  margin: 1.3rem 0;
  border-radius: 6px;
  position: relative;
  display: flex;
  align-items: center;
  font-size: 16px;
  border: 2px solid #dadada;
}
.block:hover {
  border-color: #bdbdbd;
}
.block:focus {
  border-color: red;
}
.box {
  height: 30px;
  width: 30px;
  border-radius: 50%;
  background: orange;
}
<div class="block">
  <input type="text" required/>
  <span class="label">Name</span>
</div>
<div class="block">
  <input type="password" required/>
  <span class="label">Password</span>
  <div class="box"></div>
</div>
Kyle Underhill
  • 79
  • 10
  • 29

1 Answers1

0

Here is a basic jQuery example based on your code.

$(function() {
  $("input").focus(function() {
    $(this).parent().addClass("inpFocus");
  }).blur(function() {
    $(this).parent().removeClass("inpFocus");
  });
});
body {
  padding: 1rem 2rem;
}

input {
  background: transparent;
  padding: 1rem;
  outline: none;
  border: none;
  flex: 1;
}

input:hover {
  border-color: red;
}

input:focus~.label,
input:not(:focus):valid~.label {
  color: #868ca0;
  font-weight: 700;
  border-color: red;
  top: -0.6rem;
  font-size: 14px;
  background: #fff;
  opacity: 1;
}

.label {
  position: absolute;
  left: 1rem;
  top: 1.2rem;
  pointer-events: none;
  color: #666;
  transition: 0.2s ease all;
}

.block {
  padding-right: 1rem;
  width: 300px;
  margin: 1.3rem 0;
  border-radius: 6px;
  position: relative;
  display: flex;
  align-items: center;
  font-size: 16px;
  border: 2px solid #dadada;
}

.box {
  height: 30px;
  width: 30px;
  border-radius: 50%;
  background: orange;
}

.inpFocus {
  border-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="block">
  <input type="text" required/>
  <span class="label">Name</span>
</div>
<div class="block">
  <input type="password" required/>
  <span class="label">Password</span>
  <div class="box"></div>
</div>

References

Twisty
  • 23,484
  • 1
  • 22
  • 40