【问题标题】:Gap between border and child element with border radius边框和具有边框半径的子元素之间的间隙
【发布时间】:2020-11-27 14:23:37
【问题描述】:

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

* {
  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 之间存在大约 1px 的恼人间隙:

这个问题类似于this question,但建议的解决方法对我的用例并不适用,因为我无法更改背景颜色。我也很好奇这是浏览器错误还是某种抗锯齿问题。

【问题讨论】:

    标签: html css


    【解决方案1】:

    只需在输入中添加框阴影:check + label

    input:checked + label {
        background-color: skyblue;
        box-shadow: 0px 0px 0 1px skyblue;
    }
    

    链接到Jsfiddle

    【讨论】:

      【解决方案2】:

      我不知道为什么你会得到 1 px 的差距,但你可以添加“transform: translateX(-1px);”将其向左移动 1px。这可以作为临时解决方案。

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

      【讨论】:

      • 酷,所以这也可以,另一个解决方案是将margin-left: -1px添加到label:first-of-typemargin-right: -1pxlabel:last-of-type,但我认为box-shadow方法更干净一些您不必考虑布局。
      • 是的,但我仍然不明白为什么我们会有这么烦人的差距。这些只是临时修复
      【解决方案3】:

      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>

      【讨论】:

        猜你喜欢
        • 2014-06-22
        • 1970-01-01
        • 2016-06-14
        • 2022-01-10
        • 2017-05-26
        • 1970-01-01
        • 2021-07-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多