三种颜色有角度的背景颜色

Three colors angled background color

我怎样才能获得与此图片相似的背景:

只有 3 种颜色,从顶角向外倾斜,像一道阳光。

也许坚持使用简单的 PNG 或 SVG 背景图像会是更好的方法。

可以通过 CSS 使用伪元素和转换来实现效果,下面是一个示例片段。但我认为使用 CSS 不是正确的选择。最好用PNG图片。

该代码段使用了几个具有不同背景颜色的伪元素,以所需角度倾斜以产生三色效果。

.bg {
  position: relative;
  height: 200px;
  width: 400px;
  padding: 4px;
  background: orange;
  overflow: hidden;
}
.bg:after,
.bg:before {
  position: absolute;
  content: '';
  left: 0px;
  height: 100%;
  width: 100%;
  transform-origin: right top;
}
.bg:before {
  top: 0px;
  background: red;
  transform: skewY(-45deg);
}
.bg:after {
  top: -100%;
  background: yellow;
  transform: skewY(-15deg);
}
span {
  position: relative;
  z-index: 2;
}

/* Just for demo */
.bg:hover {
  height: 200px;
  width: 500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<div class="bg">
  <span>Some content inside</span>
</div>

也可以使用成角度的线性渐变,但我认为它们不适用于动态大小的容器元素,因为角度需要随着尺寸的变化而修改以保持外观相同。

下面是使用 linear-gradient 的片段。将鼠标悬停在形状上以查看宽度 and/or 高度的变化如何影响它。

.bg {
  position: relative;
  height: 200px;
  width: 400px;
  background: linear-gradient(310deg, red 30%, transparent 30%), linear-gradient(340deg, transparent 58%, yellow 58%), orange;
  overflow: hidden;
}
.bg:hover {
  height: 200px;
  width: 500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<div class="bg">
  <span>Some content inside</span>
</div>

SVG

这可以用 SVG 来完成。 我使用了三个多边形形状。这可以设置为 background-image。 或者也可以内联使用,因此您可以在其上使用 css 属性。

html, body {
  margin: 0;
  padding: 0;
}
.triple {
  width: 250px;
  height: 250px;
}
.triple:hover {
  width: 500px;
  height: 100px;
}
<svg class="triple" viewBox="0 0 100 100" preserveAspectRatio="none">
  <polygon fill="#dd2" points="0,0 100,0 0,60" />
  <polygon fill="#bb2" points="0,60 100,0 30,100 0,100 " />
  <polygon fill="#992" points="30,100 100,0 100,100" />
</svg>

是的,可以通过渐变以响应方式完成。

假设当纵横比改变时,你不想保持角度,而是保持相对位置

诀窍是在渐变方向使用符号名称,然后调整背景图像的大小和位置

.test {
    display: inline-block;
    border: solid 1px black;
    background-image: linear-gradient(to top left, tomato 50%, transparent 50%),
    linear-gradient(to bottom right, lightgreen 50%, transparent 50%);
    background-size: 60% 100%, 100% 50%;
    background-repeat: no-repeat;
    background-position: bottom right, top left;
}

#test1 {
    width: 200px;
    height: 100px;
}

#test2 {
    width: 100px;
    height: 100px;
}

#test3 {
    width: 70px;
    height: 100px;
}
<div class="test" id="test1"></div>
<div class="test" id="test2"></div>
<div class="test" id="test3"></div>

使用 4 色 GIF 图片。这将为您提供 cross-browser/platform 兼容性和向后兼容性,并且这种类型的图像的尺寸会很小。如果颜色如图所示微妙,"jaggies" 会稍微伪装(或提供更大的尺寸)。

一个不错的选择是使用 SVG,它在现代最新的浏览器中有很好的支持。