React中的内联样式:背景线性渐变。

35

我试图使用带有线性渐变的background创建内联样式,但是样式没有被应用。

这是我的代码:

 <div className="card" style={{background:"linear-gradient(to bottom, Transparente 0%,Transparente 50%,red 50%,red 100%)"}}/>

当我为我的背景添加“简单”的颜色,也就是没有 linear-gradient 时,它可以正常工作。

<div className="card" style={{background:"red"}}/>

提前致谢。


7
没有"透明色"这个选项,请尝试使用"transparent"。 - Gabriele Petrioli
我同意@GabrielePetrioli的建议:尝试使用linear-gradient(to bottom, Transparent 0%,Transparent 50%,red 50%,red 100% - JoSSte
11个回答

32

我认为你的代码写得不正确。请参考本站点示例

<div className="card" style={{background: "linear-gradient(#e66465, #9198e5);" }}>sada</div>

17

使用此代码:

backgroundImage: "linear-gradient(to right, #4880EC, #019CAD)"

11

我有一个类似这样的东西:

<div style={{background: `linear-gradient(190deg, #fa7c30 30%, rgba(0, 0, 0, 0)30%), url(${somePic});`}}/>

这段代码之前无法正常工作,原因是在 linear-gradient 结尾处加了一个 ;。我将它删除后就可以运行了。

你是真正的MVP。 - ITJ

6

与变量一起使用的方法如下

const color1 = "#343336";
const color2 = "#B408A4";
style={{background: `linear-gradient(to bottom,  ${color1} 0%,${color2} 100%)`}}

5

所以,我看到了你的帖子,因为我也遇到了同样的问题,但是我已经找到了解决方案。

<button style={{ backgroundImage: `linear-gradient(to right, rgba(0, 224, 255, 1), rgba(0, 133, 255, 1))`, }} >

请注意,我使用了 ` 而不是 ' 来解决问题,但说实话,我不知道为什么要这么做。

5
for react version 17.0.2, i used bacgroundImage property to style div background as follows:

   <div
    style={{
      backgroundImage: "linear-gradient(yellow,lightgreen)",
      color: "darkred",
    }}
  >
    Inline style in react background: linear-gradient
  </div>

enter image description here


2
我可能有点晚了,但我找到了一个解决方法。我将其添加到CSS页面中,然后检查元素。 例如:对于*背景:linear-gradient(to right, #000 0%,#000 50%,#fff 50%#fff 100%)*; 如果您使用检查元素检查它,您会发现:-webkit-gradient(linear, left top, right top, from(#000), color-stop(50%, #000), color-stop(50%, #fff))。 因此,只需在您的React组件的内联样式中添加此最后一行即可。
<div className="card" style={{background:"-webkit-gradient(linear, left top, right top, from(#000), color-stop(50%, #000), color-stop(50%, #fff))"}}/>

为了我的示例,我使用了上面的这个而不是:
<div className="card" style={{background: linear-gradient(to right, #000 0%,  #000 50%, #fff 50% #fff 100%)"}}/>

总之,在css文件中添加这个代码,它会起作用,在“检查元素”中查看输出,并在你的React js组件的内联样式中使用和编辑它。


1
请使用以下代码添加渐变并更改值(适用于Safari和Chrome)
-webkit-gradient: (linear, left top, right top, from(rgba(0,0,0,0.5)), color-stop(50%, rgba(0,0,0,0.2)));

这是我在下面链接中的答复的重复: https://dev59.com/6FQJ5IYBdhLWcg3w2ZtT#59546630 - user9578753

0

如果你想要在行内完成这个操作,这个方法对我很有效。

<Button style={{ backgroundImage: 'linear-gradient(#f67a36,#ed008c)' }}/>

0

您拼错了transparent,应该是Transparente。正确的写法是:linear-gradient(to bottom, transparent 0%,transparent 50%,red 50%,red 100%)


3
请不要仅仅指出排版问题或缺失字符,并发布回答。这样的回答对未来的访问者没有帮助,因为它们是针对提问者的代码特定问题而言的。相反,请按照 [help/on-topic] 的规定标记或投票关闭该问题作为不适当主题。 - Blue

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