【问题标题】:Partial borders from all corners of a div CSS [duplicate]div CSS各个角落的部分边框[重复]
【发布时间】:2017-02-05 02:07:24
【问题描述】:

是否可以从每个角开始在 div 的所有边缘上都有部分边框? 我想避免 background-image 属性并使用纯 CSS 解决方案来实现这一点。

使用伪 :after 属性可以实现部分边框,但我不知道如何在所有边缘上都有它?

该 div 应该看起来像附件图像中所示的焦点小部件。

谢谢。

【问题讨论】:

  • 你写了“部分边框可以使用...”,你能分享一下代码吗?(没有)工作的方式是什么?
  • @FlorianHeer 我在这里尝试了 TrevC 提供的解决方案 stackoverflow.com/questions/4131490/…
  • @GaneshPutta“你的代码”也被抄袭了。至少可以给予信用.....
  • 为什么不使用 background-image ?有很多事情不需要额外的元素.. 灵感来自你codepen.io/gc-nomade/pen/ozZzRa 的例子,否则border-image 也做得很好:)

标签: html css css-shapes


【解决方案1】:

当然,试试这个:

HTML:

<div></div>

CSS:

div {
    background: white;
    padding: 1.7em;
    position: relative;
    width: 300px;
    height: 300px;
    margin: 3em auto;
    border: solid 2px #d00;
}
div::before, div::after {
    position: absolute;
    background: inherit;
    content: '';
    z-index: 1;
}
div::before {
    width: 100px;
    left: calc(50% - 50px);
    height: calc(100% + 4px);
    top: -2px;
}
div::after {
    height: 100px;
    left: -2px;
    width: calc(100% + 4px);
    top: calc(50% - 50px);
}
div > * {
    position: relative; z-index: 2; /* ensure any child elements sit above pseudos */
}

Fiddle.

【讨论】:

  • 如果div有内容初始化,内容将隐藏在pseudo-elements后面
  • 不,不会。阅读最终的 CSS 定义。
【解决方案2】:

您可以使用两个额外的边框元素来做到这一点,这样您就不必遮盖背景并且可以拥有透明背景。

.element {
  width: 200px;
  height: 200px;
  margin: 50px;
  position: relative;
  padding: 10px;
}
.top-border,
.bottom-border {
  position: absolute;
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 30%;
  left: 0;
}
.top-border {
  top: 0;
}
.bottom-border {
  bottom: 0;
}
.top-border:after,
.top-border:before,
.bottom-border:after,
.bottom-border:before {
  content: '';
  width: 30%;
  height: 100%;
}
.top-border:after,
.top-border:before {
  border-top: 1px solid green;
}
.bottom-border:after,
.bottom-border:before {
  border-bottom: 1px solid green;
}
.top-border:before,
.bottom-border:before {
  border-left: 1px solid green;
}
.top-border:after,
.bottom-border:after {
  border-right: 1px solid green;
}
<div class="element">
  <div class="top-border"></div>
  <div class="bottom-border"></div>
  <div class="content">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reiciendis, libero!</div>
</div>

【讨论】:

    猜你喜欢
    • 2017-06-10
    • 2020-11-08
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 2014-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多