CSS 中短边的圆边

Round edges on shorter side in CSS

我想让我的文本输入在较短的一侧(垂直的一侧)有圆角边缘。我需要的效果是这样的:

如果我使用 border-radius: 50%;,它使 corders 完全圆,我得到这个:

我需要的效果可以通过向 border-radius 提供一些随机大数来实现,这就是我所做的:border-radius: 9999px;.

有没有更好的方法,不涉及假号?

我通常选择:

border-radius: 15px;

如果打开 Inspect Element,您可以修改值以查看哪个看起来最好,而无需在服务器上编辑代码

最好、最简单、最直接的方法是以像素为单位的边界半径,正好是框高度的一半。

box {
    border-radius: __px /* Half Box Height */;
}

但是,如果您需要使用不依赖于固定像素的动态值,也总有办法。

box:after, box:before {
    border-radius: 50%;
    content: "";
    background-color: lightblue;
    top: 0;
    bottom: 0;
    position: absolute;
    width: __px /* Box Height */;
    z-index: 1;
}
box:before {
    left: 0;
    transform: translateX(-50%);
}
box:after {
    right: 0;
    transform: translateX(50%);
}
box {
    position: relative;
}

还有一个名为 calc() 的实验性 CSS 功能。将来,您可能会通过 calc() 将百分比转化为像素来实现这一点。

CSS 规则 border-radius: calc(0px+100%); 将起作用,只有在 calc() 完全开发之后。该规则会将 100% 转换为像素单位。

您还可以将 border-radius 设置为 9999px 或任何非常大的像素数,尽管此 "trick" 可能无法跨浏览器兼容。根据CSS规范...

Corner curves must not overlap: When the sum of any two adjacent border radii exceeds the size of the border box, UAs must proportionally reduce the used values of all border radii until none of them overlap.

只要使用一个巨大的数字,例如

border-radius: 9999999px;

.horizontal {
  width: 175px;
  height: 50px;
}
.vertical {
  width: 50px;
  height: 175px;
}
.box {
  border-radius: 9999999px;
  display: inline-block;
  vertical-align: middle;
  margin: 0 10px;
  background: blue;
}
<div class="horizontal box"></div>
<div class="vertical box"></div>

之所以有效,是因为根据 spec

Corner curves must not overlap: When the sum of any two adjacent border radii exceeds the size of the border box, UAs must proportionally reduce the used values of all border radii until none of them overlap.