LoginSignup
13
8

More than 5 years have passed since last update.

CSS 操作レバーをつくる。

Last updated at Posted at 2017-05-23

sample1.gif


実際に確認したい方はこちらへ
https://jsfiddle.net/junya_5102/prxz01tL/

html

<input type="checkbox" id="check1">
<label for="check1" class="leverSwitch"></label>

CSS

input#check1{
  display: none;
}

label.leverSwitch{
  position: relative;

  display: block;
  width: 9em; height: 4.6em;
  visibility: hidden;
  overflow: hidden;
}

label.leverSwitch:before{
  visibility: visible;

  content: '';
  position: absolute;
  top: 100%; left: 50%;

  width: 4.75em; height: 4.75em;
  border-radius: 100%;

  background-color: gray;
  box-shadow: 0 0 0 3px black inset;

  transform: translate(-50%,-50%);
  z-index: 2;
}

label.leverSwitch:after{
  visibility: visible;

  content: '';
  position: absolute;
  bottom: 0; left: 50%;

  width: .35em; height: 4.5em;
  border-radius: 10%;
  background-color: black;

  transform-origin: center bottom;
  transform: translateX(-50%) rotate(-75deg);
  z-index: 1;

  /* animation */
  transition: .5s ease-in-out;
}

input#check1:checked ~ label.leverSwitch:after{
  transform: translateX(-50%) rotate(+75deg);
}

解説

操作レバーの半円

操作レバーの半円部分は、正円を作り、下半分を隠して作っています。
円の下半分を親要素からはみ出すように配置します。

※ 黒の点線が親要素, 円が子要素, 赤い部分は見せる範囲, 青い部分は隠す範囲
sample2.png

はみ出た部分を隠します(見えなくします)。
隠すには親要素にoverflow: hiddenと指定します。

こんな感じに隠れます。
これで半円を作ることができました。
sample3.png


操作レバーの余白部分のクリック判定

sample4.png

※ 赤い部分が余白

上記のコードだとレバーの余白部分はクリックしてもなにも起きません
これは親要素にvisibility: hiddenと指定しているためです。

余白の部分にクリック判定を設けるにはvisibility: hiddenを消します。

ブラウザ

Chrome, Firefox, Safari で確認

13
8
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
13
8