プログラミング逆引き辞典

~ 多言語対応のプログラミングレシピ ~

「Thymeleaf」と「Bootstrap」を組み合わせたフォーム画面のサンプル

 
 

■完成画面

 
 


■ソースコード

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" th:href="@{/webjars/bootstrap/4.3.1/css/bootstrap.min.css}">
<title>顧客登録</title>
</head>
<body>
    <div class="container">
        <!-- ポイント1 -->
        <h1 class="my-3">顧客登録</h1>
        <hr class="mb-5">
        <form th:action="@{/create}" th:object="${customerForm}" method="post">
            <!-- ポイント2 -->
            <table class="table table-bordered table-striped table-hover col-md-6">
                <tr class="form-group">
                    <!-- ポイント3 -->
                    <th class="align-middle">名前</th>
                    <!-- ポイント4 -->
                    <td><input type="text" class="form-control" th:field="*{name}"></td>
                </tr>
                <tr class="form-group">
                    <th class="align-middle">メールアドレス</th>
                    <td><input type="text" class="form-control" th:field="*{email}"></td>
                </tr>
                <tr class="form-group">
                    <th class="align-middle">性別</th>
                    <td>
                        <!-- ポイント5 -->
                        <div th:each="item : ${radioGender}" class="form-check-inline">
                            <!-- ポイント6 -->
                            <input type="radio"  class="form-check-input" th:text="${item.value}" th:value="${item.key}" th:field="*{gender}">
                        </div>
                    </td>
                </tr>
            </table>
            <!-- ポイント7 -->
            <input type="submit" class="btn btn-primary" value="登録">
        </form>
    </div>
    <script th:src="@{/webjars/jquery/3.4.1/jquery.min.js}"></script>
    <script th:src="@{/webjars/bootstrap/4.3.1/js/bootstrap.min.js}"></script>
</body>
</html>

 

【ポイント】

1.マージンの設定
「class="my-3"」でmargin-topとmargin-bottomに3のマージンを設定
 
・m:margin全方向
・mx:margin-rightとmargin-left
・my:margin-topとmargin-bottom
・mt:margin-top
・mb:margin-bottom
・mr:margin-right
・ml:margin-left
※全て1~5、autoで幅を設定
 
 
2.テーブルのスタイル
・table:テーブルであることを示す
・table-bordered:テーブルの罫線
・table-striped:1行間隔で背景色を変更
・table-hover:マウスを合わせた行の色を変更
・col-md-6:768px以上の画面の場合、テーブルの幅を画面の50%にする
 
【ブレイクポイント一覧】
・576px以上:sm
・768px以上:md
・992px以上:lg
・1200px以上:xl
※尚、576未満の場合はブレイクポイント不要
 
 
3.テキストの位置
・align-middle:縦方向に中央寄せ
・align-top:縦方向に上寄せ
・align-bottom:縦方向に下寄せ
 
 
4.フォームの部品
フォームの部品は「form-group」で囲む
※その他、テキスト、テキストエリア、セレクトボックス等
 
inputタグ内に「form-control」を記述
 
 
5.ラジオボタン横並び
「form-check-inline」でラジオボタンを横並びにする
 
 
6.ラジオボタン
ラジオボタンには「form-check-input」を記述する
 
 
7.ボタン
・btn:ボタンであることを示す
・btn-primary:ボタンの色を設定
※その他の色等は公式リファレンス参照
 
Bootstrap公式リファレンス