1

I'm trying to use CSS to place a right triangle within a containing div so that the triangle takes up the full height and width of the containing div.

The height is set to 100px, so that's easy enough to handle, but the width is variable (essentially 100%) of the screen width, and I can't figure out how to get the triangle to stretch properly for a variable width.

The following is basically what I would like to get on the screen:

enter image description here

The following markup and CSS is as close as I've been able to get, but the problems I'm running into is that you can't do a percentage for a border width, and setting 100vw for the border width doesn't account for the vertical scrollbar, which causes the red triangle width to be too wide and thus add horizontal scrollbars to the site.

HTML:

<div class="container">
    <div class="triangle">
    </div>
</div>

CSS:

.container {
    background: blue;
    height: 100px;
}

.triangle {
    border-color: transparent transparent transparent red;
    border-style: solid;
    border-width: 100px 0 0 100vw;
}

Does anyone know how to solve this problem? Thank you.

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
HartleySan
  • 7,404
  • 14
  • 66
  • 119
  • Please note that the question linked to from this question does NOT work. It has the same problem as I noted in this one with using `100vw`. sol's answer below with the linear gradient works, but you get a really jagged edge. As such, I ended up basically using the above CSS, and then adding the following JS to run on page load to fix the scrollbar issue: – HartleySan Aug 01 '20 at 13:29
  • `const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;` – HartleySan Aug 01 '20 at 13:30
  • `document.querySelector('.container').style.borderLeftWidth = \`calc(100vw - ${scrollbarWidth}px)\`;` – HartleySan Aug 01 '20 at 13:31
  • This is the only solution I could find that truly worked. If there are any better solutions out there, please let us all know. – HartleySan Aug 01 '20 at 13:32
  • I made a mistake in my previous comment, the DOM selector should be `document.querySelector('.triangle')`, not `document.querySelector('.container')`. Sorry. – HartleySan Aug 01 '20 at 14:24

1 Answers1

3

.triangle {
  background-image: linear-gradient(to top right, red 50%, blue 50%);
  height: 100px;
  width: 100%;
}
  <div class="triangle">
  </div>
sol
  • 22,311
  • 6
  • 42
  • 59
  • 1
    sol, I really like the simplicity of this. It's almost a perfect solution except for the fact that the linear gradient creates a really jagged edge. As such, I'm going to continue to look for a better solution. – HartleySan Aug 01 '20 at 13:18
  • I'm trying to accomplish almost the same thing, but have that jagged edge as well. Did you find a solution? – linnse Oct 24 '22 at 15:03