LoginSignup
2
1

More than 5 years have passed since last update.

スマホでselectのテキストをセンタリングしたようなものを作る

Last updated at Posted at 2016-12-19

いろいろ参考にしたけど、CSS だけでやるより JS 使ったほうが(個人的に)楽だったという話です。
作りたかったのは、こんなセレクトボックス。

スクリーンショット 2016-12-19 14.24.28.png

Qiita:スマホでselectのテキストは左右中央にできるのか も参考にしたけど、max-device-width で iOS と Android を判別する点が好みでなく、CSS だけでやるのはやめた。

やってること

  • label と select を並べて置く
  • select を透明にし、label に重ねる
  • select 変更時に label に選択内容を反映

コードは下記です。

HTML
<ul>
  <li>
    <label for="age">年代</label>
    <select name="age" id="age">
      <option value="">年代</option>
      <option value="10">10代</option>
      <option value="20">20代〜</option>
    </select>
  </li>
  ...
CSS
li {
  list-style: none;
  position: relative;
  margin-bottom: 10px;
}
label, select {
  display: block;
  width: 200px;
  height: 30px;
  line-height: 30px;
}
label {
  background-color: #fff;
  color: #0ad;
  border: 1px #0ad solid;
  border-radius: 15px;
  text-align: center;
}
label:after {
  content: ">";
  transform: rotate(90deg);
  display: inline-block;
  margin-left: 10px;
}
select {
  position: absolute;
  top: 0;
  opacity: 0;
}

label:after は FontAwesome 使えば回転しなくていいですね。

jQuery
$('select').on('change', function () {
    var id = $(this).attr('id');
    $("label[for='"+id+"']").text($('#'+id+' option:selected').text());
});

デモ: https://jsfiddle.net/5sdw4fa6/

2
1
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
2
1