1

I want to draw a triangle diagonally on the screen which changes colour on hover. My current attempt doesn't really hover on the triangle but a 'hack triangle' which in fact is a rectangle and doesn't care about the transparent section.

How could I possibly make this hoverable only when actually hovering on the triangle itself?

body {
  padding: 0;
  margin: 0;
}

.triangle {
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 100vh 0 0 100vw;
  border-color: transparent transparent transparent #007bff;
}

.triangle:hover {
  border-color: transparent transparent transparent red;
}
<div class="triangle"></div>

The duplicate thread suggests an answer for fairly simple triangle, not like in my case where it takes up the whole width and height of the screen and each side's not identical.

LazioTibijczyk
  • 1,701
  • 21
  • 48

1 Answers1

2

You can use clip-path

body {
  margin: 0;
}

.triangle {
  width: 100vw;
  height: 100vh;
  background:#007bff;
  -webkit-clip-path:polygon(0 0,0 100%, 100% 100%);
  clip-path:polygon(0 0,0 100%, 100% 100%);
}

.triangle:hover {
  background:red;
}
<div class="triangle"></div>

For better support, I would consider skew transformation but since this should be responsive you will need some JS to adjust the angle of skewing on window resize:

var w = window.innerWidth;
var h = window.innerHeight;
document.querySelector('.triangle').style.transform="skewY("+(Math.atan(h/w)*180/Math.PI )+"deg)";

window.onresize = function(event) {
    w = window.innerWidth;
    h = window.innerHeight;
    document.querySelector('.triangle').style.transform="skewY("+(Math.atan(h/w)*180/Math.PI )+"deg)";
};
body {
  margin: 0;
  overflow:hidden;
}

.triangle {
  width: 100vw;
  height: 100vh;
  background:#007bff;
  transform-origin:top left;
  transform:skewY(20deg);
}

.triangle:hover {
  background:red;
}
<div class="triangle"></div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • @LazioTibijczyk yes it's not a surprise – Temani Afif Nov 23 '18 at 12:41
  • Considering I'd like it to be main part of the site, I'd rather make it work in all browsers. – LazioTibijczyk Nov 23 '18 at 12:42
  • @LazioTibijczyk I added another method but I had to use some JS, I don't think there is a pure CSS solution that is support in IE – Temani Afif Nov 23 '18 at 22:26
  • `"skewY("+(Math.atan(h/w)*180/Math.PI )+"deg)"`= `"skewY("+(Math.atan(h/w))+"rad)"` – Crissov Mar 15 '19 at 12:52
  • In the future (2021ish), [plain CSS will suffice](https://github.com/w3c/csswg-drafts/issues/2331): `transform: skewY(calc(atan(100vh / 100vw)))` and maybe that enclosing `calc()` will even be optional. – Crissov Mar 15 '19 at 12:58
  • @Crissov yes, exactly like I commented in the same topic https://github.com/w3c/csswg-drafts/issues/2331#issuecomment-473254797 ;) – Temani Afif Mar 15 '19 at 13:16