14
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CSSをこねくり回してフローティングラベルを制作

Last updated at Posted at 2017-08-26

フローティングラベルとGoogle検索しても、あまり引っかからないのでHTML、CSSをこねくり回して自作

実際の動きはこんな感じ
sample.gif

HTML

index.html
<form class="form">
  <p class="form__floating">
    <label class="form__floating__label" for="name">Name</label>
    <input class="form__floating__input" id="name" type="text" name="name" placeholder="名前をご記入下さい。">
  </p>
  <p class="form__floating">
    <label class="form__floating__label" for="Address">Address</label>
    <input class="form__floating__input" id="Address" type="text" name="Address" placeholder="メールアドレスをご記入ください。">
  </p>
</form>

CSS

style.css
.form {
  width: 400px;
  margin: 50px auto;
}

.form__floating {
  position:relative;
  padding-top:30px;
}

.form__floating__label {
  position:absolute;
  top:40px;
  left:10px;
  font-size:18px;
  font-weight:700;
  color:#ddd;
  transition: all 0.3s;
  cursor:text;
}

.form__floating__label.active {
  top:10px;
  left:0px;
  font-size:14px;
  font-weight:700;
  color:#000000;
  transition: all 0.3s;
}

.form__floating__input {
  width:400px;
  height:40px;
  padding:5px 10px;
  font-size:16px;
  box-sizing: border-box;
}

.form__floating__input::-webkit-input-placeholder  {
  color:transparent;
  transition: all 0.3s ease;
}

.form__floating__input::-moz-placeholder   {
  color: transparent;
  transition: all 0.3s ease;
}

.form__floating__input:-moz-placeholder   {
  color: transparent;
  transition: all 0.3s ease;
}

.form__floating__input:focus::-webkit-input-placeholder {color: #ccc;}
.form__floating__input:focus::-moz-placeholder {color: #ccc;}
.form__floating__input:-moz-placeholder {color: #ccc;}

jQuery

script.js
$(function(){
  const input = '.form__floating__input';
  const label = '.form__floating__label';

  $(input).each(function(){
    if($(this).val() != ""){
      $(this).prev(label).addClass('active');
    }
  });

  $(input)
  .focus(function(){
      $(this).prev(label).addClass('active');
    })
  .blur(function(){
    if($(this).val() == ""){
      $(this).prev(label).removeClass('active');
    }
  });
});

おわりに

こねくり回した結果、実装できました。
Googleに頼って生きてきた結果、検索に出て来ないと本当に困る。。。
簡単な方法があるよ!という方は「もう、こねくり回さなくて良いんだよ」とコメントください。

追記

初投稿にも関わらず「いいね」していただけた事を嬉しく思うと同時に、日記の様なコードを書いていたことを反省。
公開にも責任があるなーと思い、多少コードを整理しました。

また、コピペでもなんでもご自由に使っていただいて構いませんが、もろもろの責任は負いかねます。

14
11
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
14
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?