CSS入門 | CSS応用 | フォーム要素

form要素

CSSを利用すると、ユーザーの入力を受け取るinput要素にもさまざまなスタイルを設定できる。

input要素のサイズ設定

widthプロパティを利用して、input要素のサイズを設定できる。

<style>
    input { width: 100%; padding: 10px 20px; margin: 5px 0; box-sizing: border-box; }
</style>

input要素の境界線設定

borderプロパティを利用して、input要素の境界線(border)の色や太さを変更できる。 また、border-radiusプロパティを利用して、input要素の角を丸くすることもできる。

<style>
    input[type="text"] { border: solid 2px #D2691E; border-radius: 8px; }
    input[type="password"] { border: none; border-bottom: solid 2px #D2691E; }
</style>

input要素に背景色を適用

background-colorプロパティを利用して、input要素の背景色を設定できる。 また、colorプロパティを利用して、input要素のテキスト色を変更することもできる。

<style>
    input { background-color: #FFF8DC; color: olive; }
</style>

フォーカスを持つinput要素へのスタイル適用

:focus セレクタを利用して、対象のinput要素がフォーカス(focus)を持っているときのスタイルを別に設定できる。

<style>
    input[type="text"] { border: solid 2px #FFE4B5; -webkit-transition: 0.5s; transition: 0.5s; }
    input[type="text"]:focus { border: solid 2px #D2691E; }
    input[type="password"] { border: solid 1px black; }
    input[type="password"]:focus { background-color: #E0FFFF; }
</style>

input要素にアイコンや画像を挿入

background-imageプロパティを利用して、input要素にアイコン(icon)や画像を挿入できる。 また、background-positionプロパティを利用して、挿入したアイコンや画像が表示される位置を設定することもできる。

<style>
    input {
        background-image: url("/examples/images/img_search_icon.png");
        background-position: 5px 4px;
        background-repeat: no-repeat;
    }
</style>

textarea要素のサイズ調整

resizeプロパティを利用して、textarea要素のサイズを調整できる。 resizeプロパティを設定すると、そのtextarea要素の右下部分にマウスでつかめるハンドルが表示される。 ユーザーがそのハンドルをマウスでクリックして調整すると、textarea要素のサイズを自由に変更できるようになる。

CSSで使用できるresizeプロパティ値は次のとおりである。

プロパティ値 説明
none その要素のサイズを調整できない。(デフォルト設定)
both ユーザーがその要素の高さと幅の両方を調整できる。
horizontal ユーザーがその要素の幅だけを調整できる。
vertical ユーザーがその要素の高さだけを調整できる。
<style>
    textarea { width: 100%; height: 200px; box-sizing: border-box; resize: both; }
</style>

resizeプロパティはInternet Explorerではサポートされない。

select要素にスタイルを適用

CSSを利用すると、select要素にもさまざまなスタイルを適用できる。

<style>
    select {
        width: 100%;
        padding: 10px;
        border: solid 1px black;
        border-radius: 5px;
        background-color: #FFFFE0;
    }
</style>