:out-of-range

Baseline 已廣泛支援

此特性已穩定,併兼容多種裝置和瀏覽器版本。自 ⁨2015 年 11 月⁩起,所有瀏覽器均已支援此特性。

:out-of-range CSS 偽類表示一個 <input> 元素,其當前值超出了由 minmax 屬性指定的範圍限制。

試一試

label {
  display: block;
  margin-top: 1em;
}

input:out-of-range {
  background-color: orangered;
}
<form>
  <label for="amount">How many tickets? (You can buy 2-6 tickets)</label>
  <input id="amount" name="amount" type="number" min="2" max="6" value="4" />

  <label for="dep">Departure Date: (Whole year 2022 is acceptable)</label>
  <input
    id="dep"
    name="dep"
    type="date"
    min="2022-01-01"
    max="2022-12-31"
    value="2025-05-05" />

  <label for="ret">Return Date: (Whole year 2022 is acceptable)</label>
  <input id="ret" name="ret" type="date" min="2022-01-01" max="2022-12-31" />
</form>

此偽類可用於向用戶提供視覺指示,表明欄位的當前值超出了允許的範圍。

注意:此偽類僅適用於具有(且能夠接受)範圍限制的元素。在沒有此類限制的情況下,元素既不是“in-range”也不是“out-of-range”。

語法

css
:out-of-range {
  /* ... */
}

示例

HTML

html
<form action="" id="form1">
  <p>Values between 1 and 10 are valid.</p>
  <ul>
    <li>
      <input
        id="value1"
        name="value1"
        type="number"
        placeholder="1 to 10"
        min="1"
        max="10"
        value="12" />
      <label for="value1">Your value is </label>
    </li>
  </ul>
</form>

CSS

css
li {
  list-style: none;
  margin-bottom: 1em;
}

input {
  border: 1px solid black;
}

input:in-range {
  background-color: rgb(0 255 0 / 25%);
}

input:out-of-range {
  background-color: rgb(255 0 0 / 25%);
  border: 2px solid red;
}

input:in-range + label::after {
  content: "okay.";
}

input:out-of-range + label::after {
  content: "out of range!";
}

結果

規範

規範
HTML
# selector-out-of-range
選擇器 Level 4
# out-of-range-pseudo

瀏覽器相容性

另見