2016-12-02 112 views
-1

我想要一個父div填充透明背景的屏幕,但我似乎無法得到這與下面的代碼工作。CSS - 背景不透明不工作

父div只顯示爲純色。

任何想法,我做錯了什麼:

.outer { 
 
    position: relative; 
 
    z-index: 1; 
 
    background-color: rgba(255, 255, 255, 0.5); 
 
    height: 100%; 
 
} 
 
.inner { 
 
    position: absolute; 
 
    width: 100%; 
 
    top: 50px; 
 
    background-color: white; 
 
    padding: 20px; 
 
}
<div class="outer"> 
 
    <div class="inner"> 
 

 
    <h5>Search</h5> 
 

 
    </div> 
 

 
</div>

+7

您正在使用50%不透明的白色** ** 100%不透明的白色。你如何期待能夠看到? – connexo

+0

不透明的白色會是什麼樣子?非常好奇想明白。 – jdmdevdotnet

+1

你的'.outer'只有位置爲absolute的子元素。它的'height:100%;'是指父元素的高度(這裏是'body'),它是0. – connexo

回答

0

使用VH(視高度),而不是100%的高度。當你使用100%高度時,它需要100%的父母,父母是身高0px的身體。

.outer { 
 
    position: relative; 
 
    z-index: 1; 
 
    background-color: rgb(255, 255, 255, 0.5); 
 
    height: 100vh; 
 
} 
 
.inner { 
 
    position: absolute; 
 
    width: 100%; 
 
    top: 50px; 
 
    background-color: white; 
 
    padding: 20px; 
 
}
<div class="outer"> 
 
    <div class="inner"> 
 

 
    <h5>Search</h5> 
 

 
    </div> 
 

 
</div>

0

正如其他人所指出的,重疊的另一個白色元素時與白色背景上的格將無法正常工作。

但是,即使您要將.outer的顏色更改爲灰色(正如我在示例中所做的那樣),它仍然不會填滿屏幕的整個高度。

而不是使用height: 100%,您可以查看height: 100vh填滿屏幕。您可以從article瞭解有關vh(視口比例)的更多信息。

這裏有一個工作例如:

.outer { 
 
    position: relative; 
 
    z-index: 1; 
 
    background: rgba(0, 0, 0, .5); 
 
    height: 100vh; 
 
} 
 
.inner { 
 
    position: absolute; 
 
    width: 100%; 
 
    top: 50px; 
 
    background-color: white; 
 
    padding: 20px; 
 
}
<div class="outer"> 
 
    <div class="inner"> 
 

 
    <h5>Search</h5> 
 

 
    </div> 
 

 
</div>

+0

'vw'是視口**寬**,而不是視口**高**。 – connexo

+0

@connexo感謝您注意到錯字!它已被修復。 –

0

時,有對孩子一個堅實的背景和.outer因爲沒有高度所以它不可能顯示它的父div的不透明度不會實現。 (因爲position:absolute

可能會顛倒這些背景,並給位置相對將使你可以理解它如何工作如下。

注:即使在這兩個地方position:absolute;有一定道理

.outer { 
 
    position: relative; 
 
    background-color: red; 
 
    z-index: 1; 
 
    height: 100%; 
 
} 
 
.inner { 
 
    position: relative; 
 
    width: 100%; 
 
    top: 50px; 
 
    background-color: rgba(255, 255, 255, 0.5); 
 
    padding: 20px; 
 
}
<div class="outer"> 
 
    <div class="inner"> 
 

 
    <h5>Search</h5> 
 

 
    </div> 
 

 
</div>

1

你正在使用50%不透明的白色100%不透明的白色。你如何期待能夠看到?

另外,您的body的計算高度爲0。這使得.outer爲0 100% - 猜那是什麼...

html, body { height: 100%; } 
 
body { background-color: #f0f0f0; } 
 
.outer { 
 
    position: relative; 
 
    z-index: 1; 
 
    background-color: rgba(200, 0, 0, 0.5); 
 
    height: 100%; 
 
} 
 
.inner { 
 
    position: absolute; 
 
    width: 100%; 
 
    top: 50px; 
 
    
 
    padding: 20px; 
 
}
<div class="outer"> 
 
    <div class="inner"> 
 
    <h5>Search</h5> 
 
    </div> 
 
</div>