如何将渐变背景添加到文本(多行)

时间:2016-05-04 11:07:06

标签: css text background

我在互联网上找到了这个jsfiddle。你们有谁知道如何将背景颜色从白色变成渐变色?渐变颜色应该在每个新行上“重新启动”。请在此图片中查看“示例2”中的所需愿望:http://www.managers.dk/css-text-background.jpg

http://jsfiddle.net/omgmog/g3MQf/

h1 { width:480px; font:bold 36px sans-serif; letter-spacing:-1px; color:#000; }

h1 { 
background: #fff; 
display:inline; 
white-space: pre-line; 
position: relative; 
padding: 9px 0; 
line-height: 54px;
-moz-box-shadow: -20px 0 0 #fff, 20px 0 0 #fff;
-webkit-box-shadow: -20px 0 0 #fff, 20px 0 0 #fff;
box-shadow: -20px 0 0 #fff, 20px 0 0 #fff;
}

谢谢!

3 个答案:

答案 0 :(得分:4)

我不相信有一种方法可以在纯CSS中完成你想要的东西,因为没有“新行”选择器。唯一的方法是通过将文本包装到span元素中来明确定义每个新行。

body
{
    padding:50px;
    background:#fff;
}
h1
{
    width:480px;
    font:bold 36px sans-serif;
    letter-spacing:-1px;
    color:#000;
    display:inline; 
    white-space: pre-line; 
    position: relative; 
    padding: 9px 0; 
    line-height: 54px;
}
h1 span
{
    background: -moz-linear-gradient(left, rgba(148,199,247,1) 0%, rgba(32,124,229,1) 100%);
    background: -webkit-gradient(left top, right top, color-stop(0%, rgba(148,199,247,1)), color-stop(100%, rgba(32,124,229,1)));
    background: -webkit-linear-gradient(left, rgba(148,199,247,1) 0%, rgba(32,124,229,1) 100%);
    background: -o-linear-gradient(left, rgba(148,199,247,1) 0%, rgba(32,124,229,1) 100%);
    background: -ms-linear-gradient(left, rgba(148,199,247,1) 0%, rgba(32,124,229,1) 100%);
    background: linear-gradient(to right, rgba(148,199,247,1) 0%, rgba(32,124,229,1) 100%);
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#94c7f7', endColorstr='#207ce5', GradientType=1 );
}

header
{
    width: 550px;
}
<body>
  <header>
    <h1>
      <span>Some dynamic HTML text on</span>
      <span>several lines with a background</span>
      <span>that suits well and some margins</span>
      <span>around it.</span>
    </h1>
  </header>
</body>

答案 1 :(得分:1)

请查看我更新的答案。 我已添加background-attachment:fixed;以获得所需的输出。

h1 { width:480px; font:bold 28px sans-serif; letter-spacing:-1px; color:#fff; 
background: -webkit-linear-gradient(left, #085d9d 0%, #92d5ff 100%);
background: -moz-linear-gradient(left, #085d9d 0%, #92d5ff 100%);
background: -o-linear-gradient(left, #085d9d 0%, #92d5ff 100%);
background: linear-gradient(to right, #085d9d 0%, #92d5ff 100%); 
background-attachment:fixed;
display: inline;
line-height: 50px;
padding: 7px 3px;
white-space: pre-wrap;
}
    <h1>Some dynamic HTML text on several lines with a background that suits well and some margins around it.</h1>

答案 2 :(得分:1)

如果您不熟悉渐变,那么有一些工具可以帮助您更直观地进行渐变。其中一个工具是http://www.colorzilla.com/gradient-editor/,它允许您直观地构建渐变,然后单击一个按钮来复制要粘贴到CSS文件中的代码。它将为大多数主要浏览器提供浏览器安全选项。只需将其添加到您的后台CSS代码中,它就会生成您请求的结果。

我希望这有帮助!