CSS ::placeholder 伪元素

::placeholder 伪类用于设置表单元素的占位符文本的样式。
::placeholder 伪元素在 <input> 字段中选择带有占位符文本的 <form> 元素。

默认情况下,占位符文本在大多数浏览器中的外观为半透明或者浅灰色。

占位符文本是使用 placeholder 属性设置的,该属性指定了描述输入字段预期值的提示。

为了获得最大的浏览器兼容性,::placeholder 选择器与 -webkit-、-moz-、-ms- 前缀一起使用。

语法

::placeholder {
  css declarations;
}

::placeholder 选择器的例子:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      input::placeholder {
        color: #1c87c9;
        font-size: 1.2em;
        font-style: italic;
      }
    </style>
  </head>
  <body>
    <h2>::placeholder selector example</h2>
    <input placeholder="Type here...">
  </body>
</html>

表单中使用的 ::placeholder 选择器示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      * {
        box-sizing: border-box;
      }
      .container {
        margin: 20px auto;
        max-width: 250px;
        background-color: #8ebf42;
        padding: 20px;
      }
      input {
        border: 1px solid #666666;
        background-color: #eeeeee;
        padding: 15px;
        margin-bottom: 20px;
        display: block;
        width: 100%;
      }
      input::-webkit-input-placeholder {
        color: #666666;
      }
      input::-moz-placeholder {
        color: #666666;
      }
      input:-ms-input-placeholder {
        color: #666666;
      }
      input::placeholder {
        color: #666666;
      }
    </style>
  </head>
  <body>
    <h2>::placeholder selector example</h2>
    <div class="container">
      <form>
        <input type="text" placeholder="Lorem ipsum is simply...">
        <input type="date" placeholder="DD/MM/YYYY">
      </form>
    </div>
  </body>
</html>

带有 HTML <input> autofocus 属性的 ::placeholder 选择器示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      label {
        display: block;
        color: #777777;
        margin: 0 0 4px;
      }
      input {
        border: 1px solid transparent;
        padding: 15px;
        font-size: 1.2em;
        outline: 0;
      }
      input::placeholder {
        color: #8ebf42;
      }
      label,
      input {
        font-family: sans-serif;
      }
    </style>
  </head>
  <body>
    <h2>::placeholder selector example</h2>
    <form action="#">
      <div>
        <label for="name">Name:</label>
        <input id="name" name="name" type="text" placeholder="Enter your name here" autofocus>
      </div>
    </form>
  </body>
</html>
日期:2020-06-02 22:14:44 来源:oir作者:oir