【问题标题】:CSS pseudo-class :required does not work together with pseudo-element ::beforeCSS 伪类 :required 不能与伪元素 ::before 一起使用
【发布时间】:2015-12-20 15:54:01
【问题描述】:

我的意图是在必填字段的标签上加上 *。

我正在使用 Chrome 47、Firefox 43 和 Opera 34 进行测试。 这些都无法理解 CSS 选择器

span:required::before

根据http://caniuse.com/#feat=form-validation他们应该都能看懂,如果你用的话

span:hover::before

相反,它确实有效。 我做错了什么? 这是我的代码:

<!DOCTYPE HTML>
<html>
  <head>
    <style type="text/css">
      span::before {
        content: "\00A0";
      }
      span:required::before { /* This does NOT work! */
        content: "*";
      }
      span:hover::before { /* But this DOES work! */
        content: "_";
      }
    </style>
  </head>
  
  <body>
    <form>
      <p>
        <span required>Name</span>
        <input id="name" type="text" />
      </p>
      
      <p>
        <span>Date of Birth</span>
        <input id="birth" type="text" />
      </p>
    </form>
    
  </body>
</html>

【问题讨论】:

  • 我从未见过在span 元素上添加了required 属性,虽然它可能对你有用,但你不应该把它放在input 上吗?这是预期用途。

标签: css pseudo-element pseudo-class


【解决方案1】:

两个问题:

  • 表单标签有一个专用元素label。你应该使用它,而不是span

  • required 属性仅适用于控件本身,即inputselecttextarea 等。span 只是纯文本(标签为 基本上它自己)和required属性对这样的元素没有意义。1

如果您尝试为所需输入的标签设置样式,则需要为其指定类名。

这与:required::before 无关,不过,鉴于大多数表单元素都是替换元素,您不太可能同时找到那个伪类和那个伪元素。


1contenteditable尽管如此。

【讨论】:

【解决方案2】:

required 属性必须在表单控件中,您应该使用labels 而不是spans。

然后,您可以使用选择器:required + label::before。为了使它起作用,表单控件必须在 DOM 顺序中出现在标签之前,但是您可以使用浮动或弹性框来重新排列。

p {
  overflow: hidden;
}
label {
  float: left;
}
label::before {
  content: "\00A0";
  font-family: monospace;
}
:required + label::before {
  content: "*";
}
<form>
  <p>
    <input id="name" type="text" required />
    <label for="name">Name</label>
  </p>
  <p>
    <input id="birth" type="text" />
    <label for="birth">Date of Birth</label>
  </p>
</form>

【讨论】:

    猜你喜欢
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 2013-10-26
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    相关资源
    最近更新 更多