首页 > 解决方案 > 按钮未在 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>

标签: csscross-browsercss-position

解决方案


试试这个,

添加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>


推荐阅读