使用样式化组件聚焦输入时更改标签的位置

Changing the position of a label when the input is focused using styled components

我是 styled-components 的新手,我一直在尝试使用 google material 设计标准创建输入,但我无法重新创建使标签移动的动画当输入被聚焦时。

const Input = styled.input`
  font-size: 18px;
  padding: 10px 10px 10px 5px;
  display: block;
  width: 300px;
  border: none;
  border-bottom: 1px solid #757575;
  &:focus {
    outline: none;
  }
`;
const Label = styled.label`
  color: #999;
  font-size: 18px;
  font-weight: normal;
  position: absolute;
  pointer-events: none;
  left: 5px;
  top: 10px;
  transition: 0.2s ease all;
  ${Input}:focus & {
    top:-20px;
  font-size:14px;
  color:#5264AE;
  }
`;

所以在简历中,我希望标签向上移动 20px,在标签聚焦时更改其字体大小和颜色,我不确定我的方法是否正确或者只是更好在这种情况下实施正常的 CSS class。

您缺少 ~ 符号来定位输入焦点上的标签元素

const Label = styled.label`
  color: #999;
  font-size: 18px;
  font-weight: normal;
  position: absolute;
  pointer-events: none;
  left: 5px;
  top: 10px;
  transition: 0.2s ease all;
  ${Input}:focus ~ & {
    top:-18px;
    font-size:14px;
    color:#5264AE;
  }
`;

Working demo