如何创建不同颜色的左上角和右下角边框?

how to create top left and bottom right border with different color?

我正在尝试在左上角和右下角使用两种不同颜色的 div 创建边框。 找不到解决方案,有图片或直接在 css 上。

请参考下面的例子。

您可以将两个红色部分的位置设置为absolute,它们可以相对于 div 和 class box 进行定位,其中有位置设置为 relative.

.box {
  background-color: gray;
  height: 400px;
  width: 400px;
  position: relative;
}

.top-left {
  position: absolute;
  top: 10px;
  left: 10px;
  border-left: 10px solid darkblue;
  border-top: 10px solid darkblue;
  height: 30px;
  width: 30px;
}

.bottom-right {
  position: absolute;
  bottom: 10px;
  right: 10px;
  border-bottom: 10px solid red;
  border-right: 10px solid red;
  height: 30px;
  width: 30px;
}
<div class="box">
  <div class="top-left"></div>
  <div class="bottom-right"></div>
</div>

你可以效仿 Naren Murali 的例子,或者你可以创建 pseudo-elements,所以你不需要那么多 HTML。

我创建了两个伪元素:before:after

:before

在 CSS 中,::before 创建一个伪元素,它是所选元素的第一个子元素。它通常用于向内容为 属性 的元素添加装饰性内容。默认情况下是内联的。

:after

在 CSS 中,::after 创建一个伪元素,它是所选元素的最后一个子元素。它通常用于向内容为 属性 的元素添加装饰性内容。默认情况下是内联的。

div {
    position: relative;
    width: 100px;
    height: 100px;
    margin: 20px;
    background: grey;
}
div:before {
    display: block;
    content: "";
    width: 20px;
    height: 20px;
    position: absolute;
    top: 5px;
    left: 5px;
    border-top: 5px solid blue;
    border-left: 5px solid blue;
}
div:after {
    display: block;
    content: "";
    width: 20px;
    height: 20px;
    position: absolute;
    bottom: 5px;
    right: 5px;
    border-bottom: 5px solid red;
    border-right: 5px solid red;
}
<div></div>

无需额外元素或伪元素,多重背景轻松搞定:

.box {
  height: 200px;
  width: 400px;
  background:
   linear-gradient(red,red)   0 0,
   linear-gradient(red,red)   0 0,
   linear-gradient(blue,blue) 100% 100%,
   linear-gradient(blue,blue) 100% 100%,
  #ccc;
 padding:5px;
 background-size:80px 20px,20px 80px;
 background-origin:content-box;
 background-repeat:no-repeat;
}
<div class="box">
</div>