边框半径的子元素与边框之间的间隙问题

4

我正在尝试实现类似分段控件的单选按钮:

* {
  margin: 0;
  padding: 0;
}

.container {
  background-color: brown;
  width: 80vw;
}

.box {
  display: flex;
  flex-direction: row;
  border: 2rem solid skyblue;
  border-radius: 999px;
}

label {
  flex: 1;
  padding: 2rem;
  border-radius: 999px;
  text-align: center;
}

input {
  display: none;
}

input:checked + label {
  background-color: skyblue;
}
<div class="container">
  <div class="box">
    <input type="radio" id="hello" name="test" checked />
    <label for="hello">Hello</label>
    
    <input type="radio" id="world" name="test" />
    <label for="world">World</label>
  </div>
</div>

然而,在嵌套标签和父级div之间有一个约1像素的烦人间隙:

image showing gap between nested elements with border radii

这个问题类似于this question,但是建议的解决方法并不适用于我的用例,因为我不能改变背景颜色。我也很好奇这是浏览器的bug还是一种抗锯齿问题。
3个回答

5
只需将阴影添加到输入框:check + label。
input:checked + label {
    background-color: skyblue;
    box-shadow: 0px 0px 0 1px skyblue;
}

链接到Jsfiddle


2

我不知道你出现1像素间隙的原因,但你可以添加"transform: translateX(-1px);"来向左移动1像素。这可以作为一个临时解决方案。

  label {
    flex: 1;
    padding: 2rem;
    border-radius: 200px;
    text-align: center;
    transform: translateX(-1px);
  }

很棒,这个方法也可以,另一个解决方案是在label:first-of-type中添加margin-left: -1px,并在label:last-of-type中添加margin-right: -1px,但我认为box-shadow方法更加简洁,因为你不必考虑布局。 - ParadoxFox
1
是的,但我仍然不明白为什么我们会有那个烦人的间隙。这些只是临时修复措施。 - Tanish Surana

0

labelborder-radius999px 改为 35px

label {
      flex: 1;
      padding: 2rem;
      border-radius: 35px;
      text-align: center;
    }

* {
  margin: 0;
  padding: 0;
}

.container {
  background-color: brown;
  width: 80vw;
}

.box {
  display: flex;
  flex-direction: row;
  border: 2rem solid skyblue;
  border-radius: 999px;
}

label {
  flex: 1;
  padding: 2rem;
  border-radius: 35px;
  text-align: center;
}

input {
  display: none;
}

input:checked + label {
  background-color: skyblue;
}
<div class="container">
  <div class="box">
    <input type="radio" id="hello" name="test" checked />
    <label for="hello">Hello</label>
    
    <input type="radio" id="world" name="test" />
    <label for="world">World</label>
  </div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接