在元素的选定角上添加圆角边框

5

我该如何使用纯CSS构建这样的东西?

SS

迄今为止,我已经做到了这一点:Fiddle

我正在努力想方设法获得那个圆角,即使我继续添加额外的


代码:

body {
  background: #000;
}

.container {
  position: relative;
  width: 300px;
  height: 150px;
  margin: 10% auto;
}

.top-right {
  position: absolute;
  top: -10px;
  right: 0;
  width: 50px;
  height: 1px;
  background: white;
  border-radius: 5px;
}

.box {
  width: 100%;
  height: 100%;
  background: red;
  border-radius: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
}

h3 {
  color: white;
}
<div class="container">
  <span class="top-right"></span>
  <div class="box">
    <h3>Content</h3>
  </div>
</div>

2个回答

11
你可以通过在 .box 中使用伪元素 ::before/::after,并使用属性 borderborder-radius 来实现此功能。

body {
  background: #000;
}
.container {
  width: 300px;
  height: 150px;
  margin: 3% auto 0 /* changed for demo */
}
h3 {
  color: white;
}
.box {
  width: 100%;
  height: 100%;
  background: red;
  border-radius: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}
.box::before,
.box::after {
  content: "";
  position: absolute;
  border: solid white;
  width: 50px;
  height: 50px;
}
.box::before {
  top: -15px;
  left: -15px;
  border-radius: 15px 0; /* top-left */
  border-width: 5px 0 0 5px;
}
.box::after {
  bottom: -15px;
  right: -15px;
  border-radius: 0 0 15px; /* bottom-right */
  border-width: 0 5px 5px 0;
}
<div class="container">
  <div class="box">
    <h3>Content</h3>
  </div>
</div>


5

使用伪元素是理想的解决方案

这个答案只是一个替代方案。虽然不太优雅,但非常有效。

  • 创建一个包含四个div的容器。
  • 第一个div将是白色边框。
  • 最后一个div将是你的红盒子。
  • 中间的两个div将用于隐藏白色边框的区域。

HTML非常简单:

<div class="container">
    <div class="box box1"></div>
    <div class="box box2"></div>
    <div class="box box3"></div>
    <div class="box box4">
        <h3>Content</h3>
    </div>
</div>

通过绝对定位,.box2(绿色)和.box3(蓝色)可以移动以覆盖边框。

enter image description here

盒子在源中的顺序并不重要。但是使用上面的HTML代码,不需要使用z-index属性。

现在,唯一剩下的事情就是将盒子2和3的背景颜色更改为黑色。

enter image description here

完整代码:

body {
  margin: 0;
  height: 100vh;
  background-color: black;
  display: flex;
}
.container {
  position: relative;
  width: 300px;
  height: 150px;
  margin: auto;
}
.box {
  position: absolute;
  width: 300px;
  height: 150px;
  border-radius: 15px;
}
.box1 {
  border: 5px solid white;
  width: 320px;
  height: 170px;
  top: -14px;
  left: -15px;
}
.box2 {
  background-color: black;
  top: -30px;
  left: 30px;
}
.box3 {
  background-color: black;
  top: 30px;
  left: -30px;
}
.box4 {
  background-color: red;
  border-radius: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
}
<div class="container">
  <div class="box box1"></div>
  <div class="box box2"></div>
  <div class="box box3"></div>
  <div class="box box4">
    <h3>Content</h3>
  </div>
</div>


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