LoginSignup
8
9

More than 5 years have passed since last update.

ラベルがアニメーションする一行テキストフォーム

Last updated at Posted at 2016-08-21

フォーム入力時にラベルをアニメーションさせ、常に表示させるようにした一行テキストフォームです。最近では特に珍しいデザインではありませんが、作成したのでメモ。

フォームの表示結果

form2101608_02.png

フォームの特徴詳細・注意事項

  • 配置先要素内の中央に配置(配置先の状態により非確実)
  • フォーム内に入力すべき内容を促す文言を薄く表示
  • 入力中、「Name」などのラベルはフォーム外上方向へアニメーションしながら移動・小さく表示
  • 入力中、「Name」などのラベルとフォームのアンダーラインは色が変わる
  • 入力済のフォームからマウスカーソルを外すと、アンダーラインの色だけ元に戻る
  • 入力済の状態でブラウザを再読み込みすると、入力した内容はクリアされる
  • 「Name」などのラベルは、その文字の長さによってフォーム入力時に要素同士でピッタリ左揃えにはならないため、各タグにclass名を指定して個別にCSSを指定すること。

フォームのソースコード / HTML+CSS+jQuery

各プロパティの値はデザインの好みで多少微調整が必要ですが、これで次回からコピペで作れるハズ!

HTML
<form>
  <div>
    <input type="text" autocomplete="off">
    <label class="nameform">Name</label>
  </div>
  <div>
    <input type="text" autocomplete="off">
    <label class="idform">ID</label>
  </div>
  <div>
    <input type="text" autocomplete="off">
    <label class="passform">Password</label>
  </div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="js/index.js"></script>
CSS
form {
    font-family: 'ヒラギノ角ゴシック', 'Hiragino Sans', 'ヒラギノ角ゴ ProN W3', 'Hiragino Kaku Gothic ProN', 'メイリオ', 'Meiryo', 'MS Pゴシック', 'MS PGothic', sans-serif;
    width: 300px;
    margin: 20px auto 0;
}
div {
    position: relative;
    margin-top: 18px;
}
input {
    width: 100%;
    font-size: 18px;
    color: #333333;
    font-family: inherit;
    outline:none;
    border: none;
    border-bottom: 1px solid #757575;
    padding: 8px 0 3px 0;
}
label {
    font-size: 18px;
    font-weight: 300;
    color: #bbbbbb;
    position: absolute;
    left: 0px;
    top: 10px;
    pointer-events: none;
    -webkit-transition:all 0.1s ease; 
    transition: all 0.1s ease;
}
input:focus {
    border-bottom: 1px solid #4a89dc;
}
input:focus ~ label,
input.inputted ~ label {
    color: #4a89dc;
    -webkit-transform: scale(0.66);
    -ms-transform : scale(0.66);
    transform: scale(0.66);
    top: -16px;
}
input:focus ~ label.nameform,
input.inputted ~ label.nameform {
    left: -8px;
}
input:focus ~ label.idform,
input.inputted ~ label.idform {
    left: -4px;
}
input:focus ~ label.passform,
input.inputted ~ label.passform {
    left: -14px;
}
jQuery
// js/index.js
$(document).ready(function() {
    $('input').blur(function() {
        var $this = $(this);
        if ($this.val())
            $this.addClass('inputted');
    else
        $this.removeClass('inputted');
    });
});
8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9