Color border in corners seperatly

2019-02-23 22:17发布

问题:

Is there any way to color a border corner in CSS?

I.e. : border-top-left-corner-color: red

If it can't be done in pure CSS, can it be done with some JS/jQuery trickery?

回答1:

You can color each border corner seperately with 4 pseudo elements and style each corner's border color, width and style seperatly :

DEMO

.outer{
    width:500px;
    height:500px;
    background:gold;
    position:relative;
}
div:before, div:after{
    content:'';
    position:absolute;
    height:10%;
    width:10%;
}
.outer:after{
    right:0;
    border-right: 3px solid red;
    border-top: 3px solid red;
}
.outer:before{
    border-left: 3px solid green;
    border-top: 3px solid green;
}
.inner:before{
    bottom:0;
    border-left: 3px solid black;
    border-bottom: 3px solid black;
}
.inner:after{
    bottom:0; right:0;
    border-right: 3px solid blue;
    border-bottom: 3px solid blue;
}
<div class="outer">
    <div class="inner"></div>
</div>



回答2:

A little bit late ..

Here is my solution

.test {
    width: 200px;
    height: 100px;
    border: 10px solid transparent;
    background-image: linear-gradient(0deg, white 0%, white 100%),
        linear-gradient(0deg, green 0%, green 100%),
        linear-gradient(0deg, red 0%, red 100%),
        linear-gradient(0deg, yellow 0%, yellow 100%),
        linear-gradient(0deg, blue 0%, blue 100%);
    background-origin: padding-box, border-box, border-box, border-box, border-box;
    background-repeat: no-repeat;
    background-size: 100% 100%, 50% 50%, 50% 50%, 50% 50%, 50% 50%;
    background-position: top left, top left, top right, bottom left, bottom right;
}
<div class="test"></div>

The colors are achieved as 4 backgrounds set to border-box. They are then masked by a white background set to padding-box.

Notice that the thickness of the border is still set with the border property. (but the border itself is transparent)

An alternate approach, using a pseudo element to mask the inner part

.test {
    width: 200px;
    height: 100px;
    border: 10px solid transparent;
    background-image: linear-gradient(0deg, green 0%, green 100%),
        linear-gradient(0deg, red 0%, red 100%),
        linear-gradient(0deg, yellow 0%, yellow 100%),
        linear-gradient(0deg, blue 0%, blue 100%);
    background-origin: border-box, border-box, border-box, border-box;
    background-repeat: no-repeat;
    background-size: 50% 50%, 50% 50%, 50% 50%, 50% 50%;
    background-position: top left, top right, bottom left, bottom right;
    border-radius: 40px;
  position: relative;
}

.test:after {
  content: "";
  position: absolute;
  top: 0px;
  right: 0px;
  left: 0px;
  bottom: 0px;
  background-color: white;
  border-radius: 30px;
}
<div class="test"></div>