背景渐变度以适合所需宽度

时间:2018-03-20 10:51:58

标签: html css css3 linear-gradients

我有一个45deg倾斜的简单背景渐变:

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

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

如何设置渐变使得度数始终等于45(如果反转则为315),并且在任何屏幕分辨率下,我得到的顶部总是200px:

enter image description here

我还准备了一个表示我的意思的代码:https://codepen.io/Deka87/pen/JLEeXM

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

一个想法是将它分成两个渐变,第一个将覆盖200px,第二个将具有45deg并且始终具有45deg,你必须使它始终为正方形:< / p>

&#13;
&#13;
.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;
}
&#13;
<div class="top"></div>
<div class="bottom">
</div>
&#13;
&#13;
&#13;

<强>更新

如果元素的高度是动态的,只需通过保持平方比率为渐变大小指定一个大值:

&#13;
&#13;
.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;
}
&#13;
<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>
&#13;
&#13;
&#13;

<强>奖金

您还可以使用一个元素组合顶部和底部元素:

&#13;
&#13;
.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;
}
&#13;
<div class="box">
</div>
&#13;
&#13;
&#13;