Home > Software engineering >  How to create an angled 90 degree border with CSS?
How to create an angled 90 degree border with CSS?

Time:09-20

For example, something like this:

90 degree border

Is the only way of making this with pseudo elements?

CodePudding user response:

Here's a possible way to have the desired result using 1 element along with its before and after pseudo-elements.

#fancy-borders {
  position: relative;
  /* very important */
  width: 150px;
  /* change this per your requirement */
  height: 150px;
  /* change this per your requirement */
  background-color: skyblue;
  /* change this per your requirement */
  margin: 10px auto;
  /* not required for the effect to work */
}

#fancy-borders:before,
#fancy-borders:after {
  content: "";
  position: absolute;
  /** very important */
  width: 40%;
  /* change this per your requirement */
  height: 40%;
  /* change this per your requirement */
  background-color: purple;
  /* change this per your requirement */
  z-index: -1;
  /* place the pseudo elements behind the actual DIV */
}


/* pseudo-elements positionning */

#fancy-borders:before {
  bottom: -5px;
  /* change this per your requirement */
  left: -5px;
  /* change this per your requirement */
}

#fancy-borders:after {
  top: -5px;
  /* change this per your requirement */
  right: -5px;
  /* change this per your requirement */
}
<div id="fancy-borders"></div>

CodePudding user response:

.box {
  /*make it relative so absolute elements can be within its boudry*/
  position: relative;
  display: inline-block;
  height: 150px;
  width: 150px;
  background-color: blue;
}

.box::before,
.box::after {
  content: "";
  position: absolute;
  display: inline-block;
  width: 50%;
  /*half of the box*/
  height: 4px;
  background-color: black;
}


/*Settings postions for horizontal borders*/

.box::before {
  top: -4px;
  right: -4px;
}

.box::after {
  bottom: -4px;
  left: -4px;
}


/*working on vertical borders*/

.vertical-borders:before,
.vertical-borders:after {
  content: "";
  position: absolute;
  display: inline-block;
  height: 50%;
  /*half of box*/
  width: 4px;
  background-color: black;
}


/*Settings postions for vertical borders*/

.vertical-borders:before {
  top: -4px;
  right: -4px;
}

.vertical-borders:after {
  bottom: -4px;
  left: -4px;
}
<div >
  <span ></span>
</div>

CodePudding user response:

An easy solution with gradients and a few lines of code:

.box {
  width: 200px;
  aspect-ratio: 1;
  border: 5px solid #0000;
  background: 
   linear-gradient(red 0 0) padding-box,
   repeating-conic-gradient(blue 0 25%,#0000 0 50%) border-box;
}
<div ></div>

  •  Tags:  
  • css
  • Related