Web 制作のノウハウ Bootstrap

【Bootstrap】モーダル(Modal)画面を作成する

bootstrapで、モーダル画面を作成する方法を説明していきます。

モーダル(Modal)画面イメージ

上記のイメージ モーダル画面を作成するHTMLの例を記述しておきます。参考にしてみてください。

<!-- 切り替えボタンの設定 -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
 モーダルを表示
</button>

<!-- モーダルの設定 -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
 <div class="modal-dialog" role="document">
  <div class="modal-content">
   <div class="modal-header">
    <h5 class="modal-title" id="exampleModalLabel">タイトル</h5>
    <button type="button" class="close" data-dismiss="modal" aria-label="閉じる">
     <span aria-hidden="true">&times;</span>
    </button>
   </div>
   <div class="modal-body">
    <p>内容</p>
   </div>
   <div class="modal-footer">
    <button type="button" class="btn btn-secondary" data-dismiss="modal">閉じる</button>
    <button type="button" class="btn btn-primary">OK</button>
   </div><!-- /.modal-footer -->
  </div><!-- /.modal-content -->
 </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

モーダル画面はdiv.modal > div.modal-dialog > div.modal-contentと階層を作り、その中に次の3つスタイルを設定する形で、作成していきます。 

  • div.modal-header
  • div.modal-body
  • div.modal-footer

modal-headerにはモーダル画面のタイトル、modal-bodyには内容、そしてmodal-footerには各ボタンを配置します。
そして、モーダル画面を開くには モーダル画面のdivにidを付けます。

<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">

このidを呼び出し元のボタンなどから「data-target="#exampleModal"」のように指定することでモーダル画面を開くことができます。

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> モーダルを表示 </button>

モーダル(Modal)画面の詳細設定

モーダル(Modal)画面を背景クリックで閉じなくする

モーダル(Modal)の外側をクリックしてもモーダルは閉じられないようにするにはdiv.modalの場所に「data-backdrop="static"」タグを追加します。

<div class="modal fade" id="exampleModaldata-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">

モーダル(Modal)画面にスクロールバーを表示する

モーダル(Modal)画面にスクロールバーを表示するにはdiv.modal-dialogの場所に「modal-dialog-scrollable」クラスを追加します。

<div class="modal-dialog modal-dialog-scrollable" role="document">

モーダル(Modal)画面を中央に表示する

モーダル(Modal)画面を中央に表示するにはdiv.modal-dialogの場所に「modal-dialog-centered」クラスを追加します。

<div class="modal-dialog modal-dialog-centered" role="document">

モーダル(Modal)画面のサイズを変更する

モーダル(Modal)画面のサイズを変更するにはdiv.modal-dialogの場所に次のいずれかのクラスを追加します。

サイズクラスモーダルの最大幅
.modal-sm300px
標準(中)なし500px
.modal-lg800px
特大.modal-xl1140px

bootstrapで、モーダル画面を作成する方法を説明しました。
bootstrapの学習されている方のお力にされれば幸いです。

bootstrap学習書の紹介

ウェブ開発の知識とコツをしっかりマスター。
CSSフレームワークやグリッドデザインの基本から、独自テーマによるカスタマイズ方法まで。
Bootstrap4の全機能がこの1冊でわかる!一歩先を目指すWebデザイナー&Webエンジニアにおすすめ!

-Web 制作のノウハウ, Bootstrap