CSS diagonal div background

Gurbii picture Gurbii · May 3, 2017 · Viewed 20.6k times · Source

For a website I'm developing I need to include some diagonal shaped borders to a div. These are the main examples which I need to recreate.

double diagonal top border, triangle shaped

Now been scouting the web on how to achieve this, and my first thought as well would be by using ::before. However I can't get it to work without it being positioned absolute which messes up the entire page.

This is my code I have tried to achieve something like this:

Note: it won't work in here but this is the result I get result

Answer

Morfium picture Morfium · May 3, 2017

With just css and a bit tweaking based on your divs size you could create something like this:

.myclass {
width: 100px;
height: 100px;
background: linear-gradient(45deg, black 0%, black 26%, transparent 26%), linear-gradient(-45deg, black 0%, black 27%, transparent 27%)
}

.myclass2 {
width: 100px;
height: 100px;
background: linear-gradient(-45deg, blue 0%, blue 27%, transparent 27%), linear-gradient(45deg, blue 0%, blue 26%, red 26%)
}
With transparency:
<div class="myclass">My content here</div>
<br/>
Not as easy with transparent:
<div class="myclass2">My content here</div>

Edit: Just tested this in chrome, you might need special linear-gradients for older/other browsers.