CSS Forms

❮ 前章へ 次章へ ❯

CSS により、HTML フォームの外観を大幅に改善することができます:

Try it Yourself ❯

入力フィールドのスタイル

入力フィールドの幅を決定するために、width プロパティを使用します:

input {
    width: 100%;
}
Try it Yourself ❯

上の例は、すべての <input> 要素に適用されます。指定の入力タイプだけをスタイルをしたい場合は、属性セレクタを使用することができます:


入力のパディング

テキスト・フィールド内にスペースを追加するためには、padding プロパティを使用します。

チップ: お互いの後に多くの入力ある場合、外側にスペースを追加するのに、 margin を追加することもできます:

input[type=text] {
    width: 100%;
    padding: 12px 20px;
    margin: 8px 0;
    box-sizing: border-box;
}
Try it Yourself ❯
Note box-sizing プロパティに border-box を設定していることに注意してください。 これは、パディングとボーダーは最終的に要素の合計幅と高さに含まれることを確認します。
box-sizing プロパティの詳細については、CSS3 3ボックスサイズ の章をご覧ください。

ボーダー付き入力

ボーダーのサイズと色を変更するには、border プロパティを使用し、 角丸を追加するためには border-radius プロパティを使用します:

input[type=text] {
    border: 2px solid red;
    border-radius: 4px;
}
Try it Yourself ❯

下ボーダーだけを欲しい場合は、border-bottom プロパティを使用します:

input[type=text] {
    border: none;
    border-bottom: 2px solid red;
}
Try it Yourself ❯

色付きの入力

入力に背景色を追加するには、background-color プロパティを使用し、 テキストの色を変更するには color プロパティを使用します:

input[type=text] {
    background-color: #3CBC8D;
    color: white;
}
Try it Yourself ❯

フォーカスを得た入力

デフォルトで、一部のブラウザは、フォーカスを取得した(クリックした)ときに、入力の周りに青のアウトラインを追加します。 入力に outline: none; を追加することで、この動作を削除することができます。

フォーカスを取得したときに、入力フィールドを使用して何かをするため :focus セレクタを使用します:

input[type=text]:focus {
    background-color: lightblue;
}
Try it Yourself ❯

input[type=text]:focus {
    border: 3px solid #555;
}
Try it Yourself ❯

アイコン/画像付き入力

入力の内部アイコンを欲しい場合は、background-image プロパティを使用し、background-position プロパティでそれを配置します。 また、アイコンのスペースを確保するために、大きな左パディングを追加していることに注意してください:

input[type=text] {
    background-color: white;
    background-image: url('searchicon.png');
    background-position: 10px 10px;
    background-repeat: no-repeat;
    padding-left: 40px;
}
Try it Yourself ❯

アニメ付きの検索入力

この例では、フォーカスを取得した時に、検索入力の幅をアニメーション化する CSS3 transition プロパティを使用しています。 transition プロパティに関しては、後の CSS3 Transitions の章で詳細を学習します。

input[type=text] {
    -webkit-transition: width 0.4s ease-in-out;
    transition: width 0.4s ease-in-out;
}

input[type=text]:focus {
    width: 100%;
}
Try it Yourself ❯

テキストエリアのスタイル

チップ: resize プロパティは、テキストエリアがリサイズされるのを防ぐ (右下隅にある "grabber" を無効にする)ために使用します:

textarea {
    width: 100%;
    height: 150px;
    padding: 12px 20px;
    box-sizing: border-box;
    border: 2px solid #ccc;
    border-radius: 4px;
    background-color: #f8f8f8;
    resize: none;
}
Try it Yourself ❯

セレクトメニューのスタイル

select {
    width: 100%;
    padding: 16px 20px;
    border: none;
    border-radius: 4px;
    background-color: #f1f1f1;
}
Try it Yourself ❯

入力ボタンのスタイル

input[type=button], input[type=submit], input[type=reset] {
    background-color: #4CAF50;
    border: none;
    color: white;
    padding: 16px 32px;
    text-decoration: none;
    margin: 4px 2px;
    cursor: pointer;
}

/* チップ: use width: 100% for full-width buttons */
Try it Yourself ❯

CSS によるボタンのスタイル設定方法の詳細については、CSS ボタン・チュートリアルをご覧ください。


❮ 前章へ 次章へ ❯