簡體   English   中英

為什么背景圖像在CSS中比內聯背景顏色具有更高的優先級?

[英]Why is background-image having more priority in the CSS than inline background-color?

我試圖用內聯背景色覆蓋CSS中的預定義背景圖像,以為實際上可以覆蓋,但是看起來並沒有。 我該如何實現?

 .section { position: relative; top: 0; left: 0; width: 250px; height: 250px; background-image: url("https://static.pexels.com/photos/36487/above-adventure-aerial-air.jpg"); background-size: cover; } 
 <div class="section" style="background-color: rgb(250, 40, 38)"> </div> 

謝謝。

https://www.w3.org/TR/css3-background/#the-background-color

此屬性設置元素的背景色。 顏色繪制任何背景圖像的后面

您可以同時具有background-colorbackground-image 如果要覆蓋background-image ,則需要使用background: rgb(250, 40, 38)

至於為什么:

您具有以下背景屬性:

background-image
background-repeat
background-color
background-size

等等

現在,如果您設置background ,則包括所有這些屬性,因此可以指定以下內容:

background-image: url(image.jpg)

background-color: rgb(250, 40, 38)

background: rgb(250, 40, 38)

最后一個將假定沒有圖像,因為它不是在background指定的,因此將使用指定的背景色覆蓋它

只需設置background-image:none;

例如;

 .section { position: relative; top: 0; left: 0; width: 250px; height: 250px; background-image: url("https://static.pexels.com/photos/36487/above-adventure-aerial-air.jpg"); background-size: cover; } 
 <div class="section" style="background-image:none; background-color: rgb(250, 40, 38)"> </div> 

編輯:圖像具有更高優先級的原因是,如果您想使用圖像,但是對象可以擴展到圖像尺寸之外(並且您將重復設置為none),那么背景色將填充其余空間。

我認為問題在於您不僅需要為新顏色添加css,還需要為背景圖像本身添加樣式。

如果您想隱藏圖像以使顏色通過並可見,請添加

 <div class="section" style="background-color: rgb(250, 40, 38);background-image:none;"> </div> 

這應該夠了吧。 :) 希望這可以幫助

嘗試這個。 為我工作。

 .section { position: relative; top: 0; left: 0; width: 250px; height: 250px; background-image: url("https://static.pexels.com/photos/36487/above-adventure-aerial-air.jpg"); background-size: cover; } 
 <div class="section" style="background-image:none; background-color: rgb(250, 40, 38)"> </div> 

使用background代替background-imagebackground-color

.section {
  position: relative;
  top: 0;
  left: 0;
  width: 250px;
  height: 250px;
  background: url("https://static.pexels.com/photos/36487/above-adventure-aerial-air.jpg");
  background-size: cover;
}

<div class="section" style="background: rgb(250, 40, 38)">

它會工作!

編寫規范時要牢記逐步增強的意義:

使用背景圖片顯示圖片,並使用背景顏色作為舊版瀏覽器的后備廣告。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM