:optional

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

:optionalCSS擬似クラスで、 required 属性が設定されていない <input>, <select>, <textarea> 要素を表します。

css
/* 任意の <input> をすべて選択 */
input:optional {
  border: 1px dashed black;
}

試してみましょう

この擬似クラスは。フォームを送信するにあたって必須ではない入力欄にスタイルを適用するのに便利です。

メモ: :required 擬似クラスは必須のフォーム欄を選択します。

構文

:optional

省略可能なフィールドの枠を紫にする

HTML

html
<form>
  <div class="field">
    <label for="url_input">Enter a URL:</label>
    <input type="url" id="url_input" />
  </div>

  <div class="field">
    <label for="email_input">Enter an email address:</label>
    <input type="email" id="email_input" required />
  </div>
</form>

CSS

css
label {
  display: block;
  margin: 1px;
  padding: 1px;
}

.field {
  margin: 1px;
  padding: 1px;
}

input:optional {
  border-color: rebeccapurple;
  border-width: 3px;
}

結果

アクセシビリティの考慮

フォームに必須ではない <input> が含まれている場合、必須の入力欄には required 属性を適用してください。これによって、読み上げソフトなどの支援技術を使用している人が、フォームを送信するためにどの入力欄が有効なコンテンツを必要とするかを理解することができます。

必須の入力欄を視覚的に示すのに、色だけに依存しないようにしてください。通常、説明する文字列やアイコンが使用されます。

仕様書

Specification
HTML
# selector-optional
Selectors Level 4
# optional-pseudo

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
:optional

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

関連情報