sdvnksv
sdvnksv

Reputation: 9668

Background gradient degree to fit a desired width

I have a simple background gradient that is of 45deg incline:

https://codepen.io/Deka87/pen/JLEeXM

.foo-bottom {
  height: 500px;
  background: linear-gradient(315deg, green 50%, yellow 50%, yellow);;
}

How do I set the gradient such a way so that the degree is always equal to 45 (or 315 if reverse) and that the top side of the fig I get is always 200px at any screen resolution:

enter image description here

I've also prepared a codepen that shows what I mean: https://codepen.io/Deka87/pen/JLEeXM.

Upvotes: 0

Views: 308

Answers (1)

Temani Afif
Temani Afif

Reputation: 272965

An idea is to split this into two gradient, the first one will cover the 200px and the second one will have the 45deg and to always have 45deg you have to make it always a square:

.top {
  border-right: 200px solid green;
  height:30px;
  background-color: yellow;
  box-sizing:border-box;
}

.bottom {
  --h:300px;
  height:var(--h);
  background:
  linear-gradient(to top left,green 50%,yellow 50%) calc(100% - 200px) 0/var(--h) var(--h) no-repeat,
  linear-gradient(green,green)100% 0/200px 100% no-repeat;
  background-color:yellow;
}
<div class="top"></div>
<div class="bottom">
</div>

UPDATE

If the height of the element will be dynamic simply specify a big values to the gradient size by keeping the square ratio:

.top {
  border-right: 200px solid green;
  height:30px;
  background-color: yellow;
  box-sizing:border-box;
}

.bottom {
  height:50px;
  background:
  linear-gradient(to top left,green 50%,yellow 50%) calc(100% - 200px) 0/2000px 2000px  no-repeat,
  linear-gradient(green,green)100% 0/200px 100% no-repeat;
  background-color:yellow;
}
<div class="top"></div>
<div class="bottom">
</div>
---
<div class="top"></div>
<div class="bottom" style="height:100px">
</div>
---
<div class="top"></div>
<div class="bottom" style="height:600px">
</div>

BONUS

You can also combine both top and bottom element using one element:

.box {
  border-top:30px solid transparent;
  border-image:linear-gradient(to left,green 200px,yellow 200px) 1;
  height:200px;
  background:
  linear-gradient(to top left,green 50%,yellow 50%) calc(100% - 200px) 0/2000px 2000px  no-repeat,
  linear-gradient(green,green)100% 0/200px 100% no-repeat;
  background-color:yellow;
}
<div class="box">
</div>

Upvotes: 1

Related Questions