css - 按钮未在 Firefox 中相对定位的容器顶部放置
问题描述
我正在构建一个拨动开关,并且头部(按钮)并没有像我期望的那样一直定位到顶部,因为我期望它在 Firefox 中。在 Chrome 中运行良好,所以可能与默认浏览器样式有关?
编辑:我知道如何让它工作,我想知道它为什么会发生。
代码笔 https://codepen.io/warhammered_cat/pen/qBZYZVy
const toggleSwitch = document.querySelector('.toggle-switch')
const toggleSwitchHead = document.querySelector('.head')
function handleToggle(e) {
toggleSwitch.classList.toggle('active')
}
toggleSwitchHead.addEventListener('click', handleToggle)
* {
box-sizing: border-box;
}
document, body {
margin: 0;
padding: 0;
}
.head {
width: 1.25rem;
height: 1.25rem;
border: 0.125rem solid gray;
border-radius: 50%;
background-color: white;
cursor: pointer;
transition: all 0.4s;
outline: none;
box-shadow: none;
}
.rail {
height: 0.75rem;
width: 100%;
background-color: gray;
border: 0.125rem solid gray;
position: absolute;
top: 0.25rem;
z-index: -1;
border-radius: 0.3rem;
transition: all 0.4s;
}
.toggle-switch {
position: relative;
height: 1.25rem;
width: 2rem;
}
.toggle-switch.active > .head {
background-color: #F7941E;
border-color: #F7841E;
transform: translateX(1rem);
}
.toggle-switch.active > .rail {
border: 0.125rem solid #F7941E;
background-color: white;
}
<div class='toggle-switch'>
<button class='head'></button>
<div class='rail'></div>
</div>
解决方案
试试这个,
添加display:inline-flex;
到头类_
.head{
display:inline-flex;
}
点击下方查看codepen演示
结果 :
const toggleSwitch = document.querySelector('.toggle-switch')
const toggleSwitchHead = document.querySelector('.head')
function handleToggle(e) {
toggleSwitch.classList.toggle('active')
}
toggleSwitchHead.addEventListener('click', handleToggle)
* {
box-sizing: border-box;
}
document, body {
margin: 0;
padding: 0;
}
.head {
width: 1.25rem;
height: 1.25rem;
border: 0.125rem solid gray;
border-radius: 50%;
background-color: white;
cursor: pointer;
transition: all 0.4s;
outline: none;
box-shadow: none;
display:inline-flex;
}
.rail {
height: 0.75rem;
width: 100%;
background-color: gray;
border: 0.125rem solid gray;
position: absolute;
top: 0.25rem;
z-index: -1;
border-radius: 0.3rem;
transition: all 0.4s;
}
.toggle-switch {
position: relative;
height: 1.25rem;
width: 2rem;
}
.toggle-switch.active > .head {
background-color: #F7941E;
border-color: #F7841E;
transform: translateX(1rem);
}
.toggle-switch.active > .rail {
border: 0.125rem solid #F7941E;
background-color: white;
}
<div class='toggle-switch'>
<button class='head'></button>
<div class='rail'></div>
</div>
推荐阅读
- php - 在 laravel 中,如何在视图中使用 @if 语句来验证数据库条件,以便它根据条件隐藏/显示一些内容
- c - 了解 x86 上 C 函数中的汇编代码
- python - 在缺少条目的特定列变量上合并两个表/数组 (*.xlsx) 文件
- javascript - D3径向条形图覆盖而不是更新
- javascript - 从对象创建排序的嵌套列表
- algorithm - 硬币改变 dp 解决方案 - 为什么迭代循环的顺序很重要
- elasticsearch - vm.max_map_count 设置为 262144 但仍然出现错误
- kubernetes - Weavescope 仪表板显示集群中没有数据(成功安装后为空仪表板)
- botframework - 在 Teams 中以不同颜色显示来自 bot 的用户响应
- dart - 有人可以解释这段代码吗?