简体   繁体   English

输入带有移位标签字段(在所有CSS中),不需要

[英]Input with shifting label field ( in all CSS) without required

I have a floating label for a styled input done with all CSS. 我对所有CSS进行样式输入都有一个浮动标签。 The problem I am having is that this requires the input to have the required property in order to manage the moving label ( with pure CSS). 我遇到的问题是,这需要输入具有required属性才能管理移动标签(使用纯CSS)。 I am wondering if it's possible to do this without the required field because putting this in certain forms is messing with the form validations. 我想知道是否可以在没有required字段的情况下执行此操作,因为将其以某些形式放置会干扰表单验证。 My markup and CSS looks like so : 我的标记和CSS看起来像这样:

.myInput {
  position: relative;
  input {
    padding: 30px 10px 10px;
    display: block;
    width: 100%;
    border: 1px solid black;
    &:focus {
      outline: none;
    }
    &:focus~label,
    &:valid~label,
    &:placeholder-shown~label {
      top: 10px;
      color: black;
    }
  }
  label {
    color: red;
    position: absolute;
    pointer-events: none;
    left: 10px;
    top: 20px;
    transition: 0.2s ease all;
    -moz-transition: 0.2s ease all;
    -webkit-transition: 0.2s ease all;
  }
}



<div class="myInput">
  <input type="text" required id="target" />
  <label htmlFor="target">
        label
    </label>
</div>

You'll notice that if you remove the required the label no longer moves into the placeholder spot in an empty input. 您会注意到,如果删除了required的标签,则标签将不再移入空输入中的占位符位置。 Here it is in a working fiddle - https://jsfiddle.net/1ob2npcu/2/ 这是在工作的小提琴-https: //jsfiddle.net/1ob2npcu/2/

I am trying to see if there is a way to do this purely in CSS - i am using SCSS if this helps. 我试图查看是否有一种方法可以完全在CSS中执行此操作-如果有帮助,我正在使用SCSS。 Thanks! 谢谢!

If you remove the required attribute then also remove 如果删除required属性,则也删除

&:valid~label

from the CSS : then you need to define a placeholder for the input and revert the logic for the placeholder-shown pseudoclass, so the SCSS style for the input becomes CSS :那么您需要为输入定义一个占位符,并还原placeholder-shown伪类的逻辑,因此input的SCSS样式变为

input {
    padding: 30px 10px 10px;
    display: block;
    width: 100%;
    border: 1px solid black;

    &::placeholder { 
       color: transparent;
    }

    &:focus {
        outline: none;
    }

    &:focus ~ label,
    &:not(:placeholder-shown) ~ label{
        top: 10px;
        color: black;
    }

}

also, the attribute in the label is for (not htmlfor ) 同样,标签中的属性是for (不是htmlfor

fork on jsfiddle jsfiddle上的分叉

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM