2012-12-04 31 views
10

我正在研究一個HTML/CSS/JS項目,其中應用程序的大小和元素必須根據設計精確定位。由於窗口大小是固定的,因此我可以輕鬆處理CSS中的像素尺寸,而不用擔心調整瀏覽器大小。我也不必擔心IE或Opera:應用程序必須僅適用於webkit和firefox。CSS漸變顏色以像素結尾停止

在一些地方,我需要有一個漸變背景超過特定數量的像素。這東西很容易地完成像

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); 

(從灰到黑超過60像素,然後透明,然後黑色到灰色在過去的10%)。不過,我需要用像素完成相同的操作,因爲所討論的元素在不同時間的大小會有所不同。如果需要,我想避免必須使用JS以不同的動態計算的百分比重新應用梯度。

所以,我的問題:是否有指定顏色從止端X像素(而不是百分比)的方法嗎?

回答

1

我不認爲這是可能的,但覆蓋兩個對象,一個從底部不透明像素,另一個是從頂部的像素,仍然避免使用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); 
} 
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>

5

我只是通過搜索引擎過來這個開始的,另外,我認爲最好的辦法已經由瓦爾斯給出與使用多個背景圖像 - 但不是使用background-sizebackground-position我認爲它是更靈活和穩定使用阿爾法顏色在這裏(與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

+0

這是聰明的!這太糟糕了,我們不能像定位常規背景圖像那樣使用負值或「right 16px」之類的東西。 – DMack