css - triangle borders 100% of screen

2.5k views Asked by At

Desired result:

A CSS solution where I have a container with width: 100%;, and above and below the container, I have triangles attached that create a parallelogram. The triangles should cover the entire width of the screen.

Problem

I tried with transform, but that also transforms the text inside the container, so that doesn't work to create the desired form. Right now I'm trying with 2 divs, 1 above and 1 under the container, and with border-right css property. The problem here is that it doesn't accept percentages.

Code

HTML:

<div class="triangleUP"></div>
<article class="blue">
    Lorem ipsum (times 200)
</article>
<div class="triangleDOWN"></div>

CSS:

.triangleUP {
    width: 0;
    height: 0;
    border-top: 250px solid transparent;
    border-right: 1920px solid #344cd0;
    overflow:hidden;
}
.blue{
    background-color:#344cd0;
    color:white;
}
.triangleDOWN{
    width: 0;
    height: 0;
    border-top: 250px solid #344cd0;
    border-right: 1920px solid transparent;
}

JSFiddle

I know that with jQuery I could easily manipulate the property, but I'd prefer to keep it CSS only.

2

There are 2 answers

2
Emma Ramirez On BEST ANSWER

A possible solution here would be to use 100vw which is 100% of the viewport width. Here is a table of current browser support.

New CSS:

.triangleUP {
width: 0;
height: 0;
border-top: 250px solid transparent;
border-right: 100vw solid #344cd0;
overflow:hidden;
}
.blue{
    background-color:#344cd0;
    color:white;
}
.triangleDOWN{
    width: 0;
    height: 0;
    border-top: 250px solid #344cd0;
    border-right: 100vw solid transparent;
}

Result: I hope this is what you wanted it to look like

0
Alisha Alfonso On

If you want the triangle to be responsive but with a set width which is not 100% of the screen, you can use calc.

.bg{
  background: #000;
  width: 100%;
  height: 100vh;
  margin: 0;
}
.bg:after{
  content: '';
  width: 0;
  display: block;
  border-style: solid;
  border-width: calc(100vh - 50px) calc(100vw - 50px) 0 0;
  border-color: #fedbda transparent transparent transparent;
  position: absolute;
  top: 8px;
  margin: 25px;
}
<div class="bg">

</div>