在CSS

时间:2016-01-05 22:11:54

标签: html css

enter image description here

我想知道是否可以在CSS3中创建这样的背景。 背景应跨越标题div,渐变应从白色变为黑色,与屏幕宽度无关(左侧始终为白色,右侧为黑色)。

不使用图像的原因是加载时间较长,而且当浏览器小于1920px(图像的宽度)时,我无法调整它的宽度。

尝试过线性渐变,但我无法让它起作用......

此致 延

3 个答案:

答案 0 :(得分:1)

如果您还想要顶部的黑色条,您应该为背景指定尺寸,停止重复并将其放置在您想要的位置(将其视为普通背景图像

div { 
  background-color: black; 
  background-image: linear-gradient(to right, white, black); 
  background-repeat:no-repeat;
  background-size:100% 20px; /*full width, 20px height*/
  background-position:0 100%; /*gradient at bottom*/
  
  /*just to give size to demo*/
  min-height:50px;
}
<div></div>

答案 1 :(得分:0)

这里有一些CSS给你:

#grad {
  background: gray; /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(left, white , black); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(right, white, black); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(right, white, black); /* For Firefox 3.6 to 15 */
  background: linear-gradient(to right, white , black); /* Standard syntax */
} 

来源:http://www.w3schools.com/css/css3_gradients.asp

答案 2 :(得分:0)

我知道OP的问题已经回答。但是无论如何,我还是会在这里发表评论,以提供更多信息来创建真正更“复杂”的背景。

为什么 background-image ? CSS背景的基本(也是重要的)理论是:元素的背景只能有 1 background-image ,而多个background-color位于元素的顶部(即使在背景图片之后声明了背景颜色,background-image仍将放置在背景图片下方),并且您可以调整大小,重新定位这些背景图片。而且重要的是background-color被计为linear-gradient,而不是不是background-image 。上面的2个链接确实提供了有关它的所有详细信息。

以下是仅使用1个background-color HTML:OP问题中“更复杂”背景下的快速演示:

div
div { 
  background: 
    linear-gradient(to right, white, black) 0 100%/100% 20px no-repeat,
    linear-gradient(to left, white, black) 0 0/100% 20px no-repeat,
    black;
  height: 100px;
}



我很高兴写这篇长评论,因为来自一个教程 https://levelup.gitconnected.com/how-to-implement-netflix-slider-with-react-and-hooks-bdb9b99d1ce4,其中有一段内容是HTML和CSS上的冗长骇客,可实现我仅用一行CSS <div></div>就能完成的工作,我认为分享很酷, 不是吗?

background
/* simpler */

.box {
  width: 100%;
  height: 100px;
  background: linear-gradient(to right,black 0%,black 30%,transparent 75%,transparent 100%), green;
}

/* more complex */

.content {
  height: 100px;
  position: relative;
}

.background {
  display: flex;
  height: 100%;
}

.left {
  background: black;
  width: 30%;
  position: relative;
}

.left:before {
  content: '';
  position: absolute;
  background-image: linear-gradient(to right,#000,transparent);
  top: 0;
  bottom: 0;
  left: 100%;
  width: 275px;
}

.right {
  background: green;
  width: 70%;
}

.content-container {
  color: white;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 30px
}

相关问题