CSS Form animation - how does this work?

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
.input-name{
  position: relative;
  display: inline-block;
  overflow: hidden;
}
.input-name > input[type=text]{
  border: none;
  border-bottom: 2px solid red;
  outline: none;
}

.underline-animation{
  transition: all 0.5s;
  display: inline-block;
  bottom: 0;
  left: -100%;
  position: absolute;
  width: 100%;
  height: 2px;
  background-color: #64e4fe;
}
.input-name > input[type=text]:focus + .underline-animation{
  left: 0;
}

/*
a > b means selects all b where a is the parent
b + c means all c placed immediately after b

*/
</style>
</head>
<body>


 <div class="input-name">
  <input type="text" placeholder="name">
  <span class="underline-animation"></span>
</div>
</body>
</html>

The above CSS code is copied from this Stack Overflow thread. My question is: how does the span animate? I was expected to see a pseudoclass like :focus somewhere, but the only relevant line that I’ve found that can animate transition: all 0.5s;.

Also, what does display: inline-block; do?

The class underline-animation is the starting state for the span. It starts off with a left of -100% (so, off the side of the page I suppose).

The rule that changes it is

.input-name > input[type=text]:focus + .underline-animation{
  left: 0;
}

The + at the end means neighbour of. So the rule targets an underline-animation which is a neighbour of a focussed text input. This makes its left 0, and because transition is on for all properties, the change from -100% to 0 is animated.

Lastly, inline-block is like block but they share the same line. Block always drops down in the flow (goes underneath the last block) whereas inline-block can stay on the same level. Check out this SO answer. :slight_smile:

4 Likes

Ah, I see - I missed the :focus haha. Thanks for helping!

1 Like