html - 如何仅使用 CSS 和 HTML 设计带有 float 标签的 Html 输入?

标签 html css

如何像 Material Design 中那样设计一个带有 float 标签的输入文本,并且当输入未聚焦时它不会与内容重叠,我如何在不使用 Materialise.CSS 或任何其他库的情况下实现它

最佳答案

我更喜欢这种技术,因为它的标记简单、可访问性和键盘友好性。

它使用相对定位和绝对定位(相对容器内的绝对标签)并且永远不会用另一个元素(例如占位符伪元素)“替换”标签,因为根据我的经验,替换技术会导致闪烁。它还管理指针事件,以便标签永远不会妨碍单击以选择输入(但一旦它离开,它的文本是可选择的)。

我使用了 em,因为我们要处理动画文本。这应该允许该技术缩放到不同的字体大小,而无需修改用于填充和边距的偏移量。

这使用 required 属性和 :valid 选择器来检查输入是否留空(在这种情况下,标签会下降)。如果这对您的用例不起作用,可以通过使用 JavaScript 在输入中添加和删除 empty 类来解决(这就是最后一个 CSS 规则集的用途)。另一种选择是使用 :placeholder-shown 和一个虚拟占位符,如果你不支持 Microsoft Edge。记住,CSS's :empty selector doesn't work the way you'd think it might on HTML inputs .

@import url('https://fonts.googleapis.com/css?family=Roboto');

body
{
  /* just to make it feel a little more at home */
  font-family: 'Roboto', sans-serif;
}

.floating-label
{
  position: relative;
  margin-top: 1.75em;
}

.floating-label input[type="text"]
{
  border: none;
  border-bottom: 1px solid gray;
  margin-bottom: 1px;
}

.floating-label input[type="text"]:hover
{
  border-bottom: 2px solid black;
  margin-bottom: 0;
}

.floating-label input[type="text"]:focus,
.floating-label input[type="text"]:active
{
  outline: none;
  border-bottom: 2px solid #2196f3;
  margin-bottom: 0;
}

.floating-label input[type="text"] + label
{
  position: absolute;
  pointer-events: none;
  bottom: 0.1em;
  left: 0.1em;
  color: gray;
  font-size: 1.0em;
  transition: margin 0.2s ease,
              color 0.2s ease,
              font-size 0.2s ease;
}

.floating-label input[type="text"]:focus + label,
.floating-label input[type="text"]:active + label,
.floating-label input[type="text"]:valid + label
{
  pointer-events: auto;
  margin-bottom: 1.75em;
  font-size: 0.7em;
}

.floating-label input[type="text"]:focus + label,
.floating-label input[type="text"]:active + label
{
  color: #2196f3;
}

.floating-label input[type="text"].empty:not(:focus) + label,
.floating-label input[type="text"].empty:not(:active) + label
{
  pointer-events: none;
  margin-bottom: 0;
  color: gray;
  font-size: 1.0em;
}
<div class="floating-label">
  <input id="first" type="text" required>
  <label for="first">First Name</label>
</div>
<div class="floating-label">
  <input id="last" type="text" required>
  <label for="last">Last Name</label>
</div>

关于html - 如何仅使用 CSS 和 HTML 设计带有 float 标签的 Html 输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52124206/

相关文章:

javascript - 如何让一个按钮对应不同的点击div html jquery php?

html - 在复选框旁边 float 一个 div

html - 通过css修改不同的列表

javascript - 使用jquery发起自定义事件

javascript - 当前 View 的位置

java - 将图表导出为 html - 在应用程序中打开 html 时丢失图像。如何设置图片的绝对路径

javascript - 如何在没有 jQuery 插件的情况下格式化输入电话号码?

javascript - DIV 隐藏元素间距调整

html - 仅使用 CSS 更改段落中的单个单词背景(不更改 HTML)

CSS 导航栏卡在 DIV 后面