如何设计"overflowing" css <div> 的边框线?

How to design "overflowing" border lines of css <div>?

刚刚进入 css,虽然尝试了不同的方法,但我无法设计出符合我心目中边框的内容框。它应该看起来像这样:

换句话说:边界应该相互交叉并持续大约 30px,也许我们可以称之为溢出。导致所有四个边都出现交叉。

我尝试在每个边上设计一个小的立方体盒子,它有点管用。但我发现很难将它们包含在我的响应性概念中,因为它们不会以与实际盒子(我们称之为 <box>)相同的速度收缩。 <box> 有边距百分比,所以当页面被缩小时,小框 <sbox> 挡住了我的路,阻止了 <box> 的边距一直延伸到边框。

关于如何使那个更优雅的任何想法?

您可以使用 beforeafter 伪 类 的帮助来完成此操作。

* { box-sizing:border-box; }
.box { padding:20px; width:100px; height:100px;  position:relative;  border-left:2px solid #000; border-right:2px solid #000;  }

.box::after { position:absolute; top:5px; left:-7px; background:#000; width:110px; height:2px; content:"";}

.box::before { position:absolute; bottom:5px; left:-7px; background:#000; width:110px; height:2px; content:"";}
    <div class="box">
      Content
    </div>

Demo

没有伪造的例子类

.outer{
  height: 1em;
  margin: 0 1em 0 1em;
}

.content{
  border: 1px solid #000;
  border-left: none;
  border-right: none;
}

.innerContent{
  margin: 0 1em 0 1em;
}

.borderLeftRight{
  border-left: 1px solid #000;
  border-right: 1px solid #000;
}
<div class="outer borderLeftRight"></div>
<div class="content">
  <div class="innerContent borderLeftRight">
    Content
  </div>
</div>
<div class="outer borderLeftRight"></div>

有人已经做过类似的事情。我认为最优雅的方式是使用伪选择器 :before & :after。我觉得你应该这样做,而不是用包装纸。最重要的事情是将元素的 position 设置为 relative,然后将选择器的前后位置设置为 absolute。然后 fiddle 具有 bordertopbottomleftright 属性。

.box {
  display: inline-block;
  position: relative;
  padding: 2em;
}
.box:after,
.box:before {
  position: absolute;
  content: "";
}
.box:after {
  border-top: 1px solid #f00;
  border-bottom: 1px solid #f00;
  left: 0;
  right: 0;
  top: 1em;
  bottom: 1em;
}
.box:before {
  border-left: 1px solid #f00;
  border-right: 1px solid #f00;
  left: 1em;
  right: 1em;
  top: 0;
  bottom: 0;
}
<div class="box">
  text inside
</div>

只是将其放在这里是为了说明您可以使用单个伪元素来完成此操作。

固定宽度

您必须为其设置宽度和高度,可以使用 calc 解决此问题,但它的支持还不是很出色。

* {
  box-sizing: border-box;
}
div {
  width: 300px;
  height: 200px;
  border-top: 1px solid;
  border-bottom: 1px solid;
  margin: 100px;
  position: relative;
  padding: 10px 25px;
}
div:after {
  content: "";
  display: block;
  position: absolute;
  top: -20px;
  left: 20px;
  width: 260px;
  height: 240px;
  border-left: 1px solid;
  border-right: 1px solid;
}
<div>Testing</div>


自动宽度

示例使用 calc,这适用于任何大小的文本。

* {
  box-sizing: border-box;
}
div {
  width: 300px;
  height: 200px;
  border-top: 1px solid;
  border-bottom: 1px solid;
  margin: 100px;
  position: relative;
  padding: 10px 25px;
}
div:after {
  content: "";
  display: block;
  position: absolute;
  top: -20px;
  left: 20px;
  width: calc(100% - 40px);
  height: calc(100% + 40px);
  border-left: 1px solid;
  border-right: 1px solid;
}
<div>Hello</div>