Search code examples
csscss-shapes

CSS triangle border-width does not work with percentage value relative to the parent


I made a right-angled triangle with this CSS code:

height: 0;
border-width: 0 0 100px 1000px;
border-color: transparent red red transparent;
border-style: solid; 

The problem is, I cant use % instead of px.

I want to make right-angled triangle width 100% but it totally does not work. I know I can add width:100%; but the triangle won't look good and I will have to adjust the diagonal line with px. that is not handy. because if I make the window smaller, the triangle wont scale.

Can someone help me to fix this problem?


Solution

  • border-width cannot have a percentage value. The permitted values are:

    <line-width> = <length> | thin | medium | thick

    Where <length> is a <number> followed by length units: px, em, rem, ....


    That being said, one possible CSS option is to use viewport relative unit vw to set the width of the border according to the width of the viewport.

    In that case, you just need to calculate the width of the parent element relative to the width of the viewport. If the parent fill the entire horizontal space, go with 100vw; If it fills the half of viewport: 50vw and so on.

    body { margin: 0; }
    
    div {
      height:0;
      border-width:0 0 100px 100vw;
      border-color:transparent red red transparent;
      border-style:solid;
    }
    <div></div>

    It's worth mentioning that vw viewport percentage length is supported in IE9+.