我正在尝试用CSS属性找到最简单的方法来垂直对齐我的类似iOS的切换按钮,以便看起来更漂亮。
我不想使用第二个div - container..我只想将div.switch-btn::移到.switch-btn中间
<!DOCTYPE html>
<html>
<title>iOS Toogle Switch</title>
<style>
.switch{
opacity: 0;
}
.switch-btn{
width: 80px;
height: 20px;
background: #e5e5e5;
position: relative;
border-radius: 20px;
box-shadow: inset 0 3px 10px rgba(0,0,0,.3);
}
.switch-btn:before{
content: "";
position: absolute;
height: 36px;
width: 36px;
background: linear-gradient(#FFF, #f2f2f2);
left: 2px;
top: 2px;
transition: all 250ms ease-out;
cursor: pointer;
border-radius: 50%;
box-shadow: 0 8px 6px -4px rgba(0,0,0,.25);
}
input[type=checkbox]:checked + .switch-btn {
background: #47CB8F;
}
input[type=checkbox]:checked + .switch-btn:before {
left: 42px;
}
</style>
<body>
<label class="switch">
<input type ="checkbox"/>
<div class="switch-btn"></div>
</label>
<script>
</script>
</body>
</html>
发布于 2018-07-16 03:07:55
https://jsfiddle.net/2ehmwta3/
.switch-btn:before {
/* ... */
top: 50%;
transform: translateY(-50%);
/* ... */
}
当你想让一些东西垂直居中时,即使目标DOM比父元素大,你也应该设置transform
属性。
解释
.switch-btn:before
的高度为36px,但您给出的top: 2px
距离父DOM对象(switch-btn
)的顶部位置仅向下移动2个像素。
所以我给了top: 50%
,它会把.switch-btn:before
放在离最上面的位置10个像素的地方,因为你知道20 (the height of '.switch-btn') * 50% = 10
。
而且,最重要的部分是transform: translateY(-50%)
。这使得DOM移动到自身高度的一半。所以.switch-btn:before
会向上移动18个像素。
https://stackoverflow.com/questions/51351316
复制相似问题