Bootstrap5 Formsまわりの諸設定

Bootstrap5のフォームを設定する上で、細かい諸設定についてまとめておく。

https://getbootstrap.jp/docs/5.0/forms/overview/

基本形

<form>
  <div class="mb-3">
    <label for="exampleInputEmail1" class="form-label">Email address</label>
    <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
    <div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div>
  </div>
  <div class="mb-3">
    <label for="exampleInputPassword1" class="form-label">Password</label>
    <input type="password" class="form-control" id="exampleInputPassword1">
  </div>
  <div class="mb-3 form-check">
    <input type="checkbox" class="form-check-input" id="exampleCheck1">
    <label class="form-check-label" for="exampleCheck1">Check me out</label>
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

メールアドレスを入力させるフォームを軸に、さらにシンプルにする。

<form>
    <label for="exampleInputEmail1" class="form-label">Email address</label>
    <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
    <div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

labelに設定されているforプロパティは、labelとフォームを紐づける役割がある。この場合だと、labelのforとinputのidが対応している。

スクリーンリーダーでの利便性が上がるのと、ラベルクリック時にもフォームがアクティブになるなどの利点もある。

inputのaria-describedbyプロパティは、そのオブジェクトを説明するテキストのIDを指定する。この場合、div#emailHelp同士が対応しており、スクリーンリーダーなどで読み上げられる。

入力禁止のdisableとreadonly

入力内容の確認画面などで便利な入力禁止されたフォームも簡単に実装できる。

valueが入っている場合は選択してコピーなども可能。

https://getbootstrap.jp/docs/5.0/forms/form-control/?#disabled

<!-- disabledを追加すると、ポインターも変化しない -->
<input class="form-control" type="text" placeholder="Disabled input" aria-label="Disabled input example" disabled>

<!-- readonlyを追加すると、ポインターで選択することは可能 -->
<input class="form-control" type="text" placeholder="Disabled input" aria-label="Disabled input example" disabled>

一方で、入力確認時にフォームっぽく見せたくない時もある。その場合はreadonlyはそのままで、.form-control-plaintextを追加する。

https://getbootstrap.jp/docs/5.0/forms/form-control/?#readonly-plain-text

<label for="staticEmail" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
    <input type="text" readonly class="form-control-plaintext" id="staticEmail" value="email@example.com">
</div>

この方法だと、背景のグレーアウトは行われないのでプレーンなテキストが出力される。余白などはそのまま維持されるので、他のフォームと混在させてもレイアウトが崩れることがない。

このサイトの主
投稿を作成しました 115

関連投稿

検索語を上に入力し、 Enter キーを押して検索します。キャンセルするには ESC を押してください。

トップに戻る