In my opinion, opting for an hr
instead of a div
(as it essentially functions as a rotated horizontal rule) would be a better choice. Nevertheless, achieving this using CSS is definitely possible. It does require some functionalities that, currently, only function in Safari and Firefox: the CSS sqrt() and atan2 functions.
We can define the width of our hr
to match the hypotenuse of your triangle, and apply rotation using atan2
(for further insights on this unique function, refer to its wikipedia article. Its significance reaches to the extent of being directly integrated into CPUs as a fundamental machine instruction) to determine an angle based on distance and rise:
main {
--w: 200;
--h: 100;
width: calc(1px * var(--w));
height: calc(1px * var(--h));
background: red;
}
.line {
padding: 0;
margin: 0;
height: 0px;
border: 0.5px solid black;
transform-origin: 0 0;
/* line from (0,0) to (50% width, 50% height): */
--lw: calc(var(--w) / 2);
--lh: calc(var(--h) / 2);
/* calculate our hypotenuse length and angle: */
--m: calc(pow(var(--lw), 2) + pow(var(--lh), 2));
--hyp: sqrt(var(--m));
width: calc(1px * var(--hyp));
--angle: atan2(var(--lh), var(--lw));
transform: rotate(var(--angle));
}
<main>
<hr class="line"/>
</main>
Naturally, resorting to SVG would offer a much simpler solution with improved compatibility =D