Todilo Todilo - 1 month ago 13
CSS Question

Css background arrow percentage width

I have a box with a "cool" looking triangle background (covers 50% of the box). I solved for any fixed width but forgot that on mobile the width is not fixed anymore, making my solutions to fail on mobile devices.

To create the background, I use border technique setting each side of the border to half of the height/width, but, borders cant be in percentage (%).

How can I possibly achieve that?

Below is my code:

.outer {
width: 100%;
height: 300px
}
.background-triangle {
bottom: 0;
right: 0;
height: 0;
width: 0;
border-right: 250px solid rgba(0,0,0,.1); /* half width */
border-bottom: 150px solid rgba(0,0,0,.1);/*half height*/
border-left: 250px solid transparent;/*half width*/
border-top: 150px solid transparent; /* half height*/
}

.box-color {
position: relative;
background-color: #6699cc;
}


and a very straightforward html

<div class="outer">
<a href="/#">
<div class="box-color" style="">
<div class="background-triangle"></div>
</div>
</a>
</div>


I would prefer a non-javascript option if possbile. I guess I could set the width when the window size changes.

Edit: What I want to achieve is to make the black background triangle stretch the full width of its containing element. Try resizing the jsfiddle window and see how the triangle has a fixed width. It does not follow the containing "blueish" box width change. I hope this clears the question up.

And a jsfiddle link

Answer

Use linear background instead of traditional triangle generation technique. Check this solution at this updated jsFiddle: https://jsfiddle.net/ashekthegreat/kmmg9L01/6/

.background-triangle {
  width: 100%;
  height: 100%;
  left: 0px;
  top: 0px;
  background: linear-gradient(to right bottom, transparent 50%, rgba(0, 0, 0, .1) 50%)
}
Comments