CSS中使用百分比实现渐变色。

5

我只有基本的CSS知识。根据以下指南,我正在尝试为我的一个项目提供渐变色,并且应该是垂直方向的。

enter image description here

我尝试了下面的代码,但只有第一种颜色显示在整个区域中。我不理解30%和50%的含义。如何实现这个效果?

 .myheader {  
  background: linear-gradient(to bottom, #mycolor1 85%, #mycolor2 45%, #mycolor3 10%);       
  }

不确定您从哪里获取这些数字,但是 background: linear-gradient(to bottom, blue, red); 应该可以实现。 - Paulie_D
5个回答

2
你需要按升序指定点。只需反转你拥有的值(如果需要,可以添加紫色):

body {
  height: 100vh;
  overflow: hidden;
  background: linear-gradient(to bottom, blue 15%, red 90%) center/cover no-repeat;
}


谢谢!我还想了解一下图片中提到的30%和50%是什么?这是我需要担心的问题还是不需要关注? - Arun Palanisamy

2
每个人都在提供“到底部”的解决方案,但琐碎的解决方案是考虑“到顶部”,并保留您在图片中使用的百分比值。原始答案翻译成“最初的回答”。
linear-gradient(to top, #mycolor3 10%, #mycolor2 45%, #mycolor1 85%);

例子:

最初的回答

body {
  background: linear-gradient(to top, red 10%, purple 45%, blue 85%);
  margin: 0;
  height: 100vh;
}

关于(50%和30%之间的比例),它们可能是颜色提示(也称为颜色插值提示)。来自新规范

在两个颜色停止点之间可以有一个颜色插值提示,它指定了两侧颜色停止点之间的空间中颜色应如何插值(默认情况下,它们进行线性插值)。在任何给定的两个颜色停止点之间最多只能有一个颜色插值提示;使用多个会使函数无效。

例子:

body {
  background: 
   /* First gradient with hints*/
   linear-gradient(to top, red 10%, purple 45%, blue 85%) left /45% 100%,
   /* Second gradient with hints*/
   linear-gradient(to top, red 10%,27.5% ,purple 45%, 57% ,blue 85%) right/45% 100%;
  
  
  background-repeat:no-repeat;
  margin: 0;
  height: 100vh;
}


非常好的解释!非常感谢您澄清了我对那些神秘百分比的疑惑 :) - Arun Palanisamy
@ArunPalanisamy 欢迎 ;) 顺便说一下,你是在哪里找到创建渐变的工具的?我想试试,并通过设置不同的值来确保我所说的是正确的...颜色提示部分可能比这更棘手。 - Temani Afif
抱歉,我不知道 :( 。这在我的公司的设计文档中提到了。我截了屏并放在这里。我只是按照那些文件来设计我的应用程序。 - Arun Palanisamy
@ArunPalanisamy 好的,所以只有公司知道那些额外百分比的真正含义。很有可能它们是颜色提示,但也可能不是。 - Temani Afif

1

 .myheader {
  width: 100px;
  height: 100px;
  background: linear-gradient(to bottom, blue 15%, purple 45%, red 90%);       
 }
<div class="myheader"></div>

“to bottom” 方向指明了渐变从上往下的方向。因此,如果第一个颜色设置为 85%,表示渐变将会在容器高度的 85% 处结束。
通过将百分比反转(85% 变成 15%),您可以实现所需的效果。

成功了!谢谢。你知道图片中提到的30%和50%是什么吗? - Arun Palanisamy

0

这是一个例子,使用您的rgba颜色。

.myheader {  
  background: linear-gradient(to bottom, rgba(248,80,50,1) 0%, rgba(241,111,92,1) 50%, rgba(246,41,12,1) 51%, rgba(240,47,23,1) 71%, rgba(231,56,39,1) 100%
  }

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接