CSS渐变颜色从像素中停止

时间:2012-12-04 17:31:06

标签: css3 linear-gradients css

我正在开发一个HTML / CSS / JS项目,其中应用程序是固定大小的,并且元素必须根据设计精确定位。由于窗口大小是固定的,我可以轻松使用CSS中的像素尺寸,而不用担心调整浏览器的大小。我也不用担心IE或Opera:应用程序必须只能在webkit和firefox中使用。

在一些地方,我需要有一个超过特定像素数的渐变背景。这可以通过

之类的东西轻松完成
background-image: linear-gradient(to top, #666666, #000000 60px);

(以及它的-webkit--moz-对应物。)这为大多数元素提供了技巧。然而,有一些我需要有颜色停止的顶部和底部像素位置。如果这些是百分点,那么可以通过以下方式完成:

background-image: linear-gradient(to top, #666666, black 60px, transparent 60px, transparent 90%, black 90%, #666666);

(从灰色到黑色超过60px,然后透明,然后是黑色到灰色,最后10%)。但是我需要用像素来完成相同的操作,因为所讨论的元素在不同的时间大小不同。如果需要,我想避免使用JS在不同的动态计算百分点重新应用渐变。

所以,我的问题是:有没有办法从结尾指定色卡 x 像素(不是百分比)?

4 个答案:

答案 0 :(得分:6)

我刚刚通过搜索引擎来看看这个问题,我认为使用多个背景图片的val已经给出了最佳解决方案 - 但不是使用background-sizebackground-position我认为在这里使用 alpha颜色(使用rgba())会更加灵活和稳定,如下例所示:

background-image:
    /* top gradient - pixels fixed */
    linear-gradient(to bottom, rgb(128,128,128) 0px,rgba(128,128,128,0) 16px), 
    /* bottom gradient - pixels fixed */
    linear-gradient(to top, rgb(128,128,128) 0px, rgba(128,128,128,0) 16px),  
    /* background gradient - relative */
    linear-gradient(to bottom, #eee 0%, #ccc 100%) ;

这给了我最初搜索的行为。 :)

演示:http://codepen.io/Grilly86/pen/LVBxgQ

答案 1 :(得分:1)

我不认为这是可能的,但覆盖2个对象,一个从底部有不透明像素,另一个用顶部像素,仍然会避免使用JS

.background {
    position: absolute;
    background-image: linear-gradient(to top, #666666, black 60px, transparent 60px);
}
.overlay {
    position: relative;
    background-image: linear-gradient(to bottom, #666666, black 60px, transparent 60px);
}

答案 2 :(得分:1)

在po228的上一个答案的行中,但是在相同的元素背景中。

设置2个不同的渐变,一个从顶部开始,另一个从底部开始

.test {
  background: linear-gradient(to top, red 10px, white 10px),
      linear-gradient(to bottom, blue 10px, white 10px);
  background-size: 100% 50%;
  background-repeat: no-repeat;
  background-position: bottom center, top center;
  height: 150px;
  width: 300px;
}
<div class="test"></div>

答案 3 :(得分:0)

适用于calc(),但遗憾的是不适用于MS浏览器:

每对的第一行有2个背景堆叠的解决方案,第2行有使用的calc。不适用于Internet Explorer和Edge浏览器。

&#13;
&#13;
div {
  margin-left: auto;
  margin-right: 0;
  width: 200px;
  height: 20px;
  animation: sweep 5s ease-in-out alternate infinite;
  text-align: center;
  color: white;
  font-family: sans-serif;
  font-weight: bold;
  line-height: 20px;
  will-change: width;
}

div:nth-child(odd) {
  background-image: linear-gradient(to right, red, green 100px, transparent 101px), linear-gradient(to left, red, green 100px);
  border-bottom: 1px solid gray;
}

div:nth-child(even) {
  background-image: linear-gradient(to right, red, green 100px, green calc(100% - 100px), red);
  margin-bottom: 10px;
}

div:nth-child(n+3) {
  width: 300px;
}

div:nth-child(n+5) {
  width: 400px;
}

div:nth-child(n+7) {
  width: 500px;
}

div:nth-child(n+9) {
  width: 600px;
}

@keyframes sweep {
  100% {
    width: 600px;
  }
}
&#13;
<div> 200 </div>
<div></div>
<div> 300 </div>
<div></div>
<div> 400 </div>
<div></div>
<div> 500 </div>
<div></div>
<div> 600 </div>
<div></div>
&#13;
&#13;
&#13;