如何在单行中设置逆梯度

时间:2016-01-04 09:57:35

标签: html css gradient linear-gradients

我修正了对角线渐变的类似问题。 现在线性很困难。

我能够用十字架创建一个渐变

background: linear-gradient(to right, transparent 40%,#f00 50%,transparent 60%), 
            linear-gradient(to bottom, #fff 20%,#f00 50%,#fff 80%);

我无法创建一个渐变,在左半部分中有一个渐变到底部白色 - 红色,而在右半部分则是反向渐变RED-WHITE。

以下是我尝试创建它的方式:

background: linear-gradient(to bottom, transparent 50%,#ff0 100%), 
            linear-gradient(to right, transparent 50%,#f00 100%);

但黄色部分已满!我该如何解决这种情况?

这就是我想要的:

enter image description here

2 个答案:

答案 0 :(得分:2)

使用单个元素和单个背景规则可以实现此目的。只需在X轴上给每个渐变50%的容器尺寸,使用background-position在左侧放置一个渐变,在右侧放置另一个渐变,并通过设置{{的值来停止渐变重复1}}为background-repeat

no-repeat
div {
  height: 100px;
  background: linear-gradient(to top, red 10%, yellow 50%), linear-gradient(to bottom, red 10%, yellow 50%);
  /* background-size: 50% 100%; Ideally this should be enough but it leaves a white line in the middle in snippet for some reason and so use below setting */
  background-size: 50% 100%, calc(50% + 1px) 100%;
  background-position: 0% 0%, 100% 0%;
  background-repeat: no-repeat;
}

答案 1 :(得分:1)

修改:可以使用一个background,请参阅Harry's answer

在您的元素上使用单个background规则无法直接实现,但可以使用::before::after伪元素。

div {
  width: 100%;
  height: 50px;
  border: 1px solid black;
  position: relative;
  background: linear-gradient(to bottom, red 0%, #ff0 100%);
}
div::before {
  content: "";
  position: absolute;
  left: 50%;
  right: 0;
  top: 0;
  bottom: 0;
  background: linear-gradient(to top, red 0%, #ff0 100%);
}
<div></div>