2017-02-17 73 views
2

是否可以將背景顏色設置爲一個元素(在我的情況下svg),但背景的大小是小於實際元素?設置背景顏色,但不是整個背景

可以說你有一個300px寬和300px高的div。 我想將背景顏色設置爲200px x 200px的區域。

<object class="tapes" width="40%" type="image/svg+xml" data="element.svg"> 

爲什麼我問?因爲我的元素包含透明度

+4

您可以創建在SVG一個矩形,並把它作爲最底層的元素。 – Shilly

+0

酷我在我的svg代碼中添加了一個新的矩形。不幸的是,我無法通過css訪問它並設置其背景顏色。 – sanjihan

+0

只需使用內聯屬性。 '填' ? – Shilly

回答

1

我不知道這會爲一個SVG對象的工作,但它會在HTML和CSS工作。你可以做的是將box-sizing屬性設置爲border-box,然後給該元素一個border,其顏色與父元素的background-color相同。在下面的示例中,我將父母的background-color和孩子的border-color設置爲不同的值,以便您瞭解實際發生的情況。

body { 
 
    width: 100%; 
 
    height: 185px; 
 
    overflow-x: hidden; 
 
    display: flex; 
 
    justify-content: center; 
 
    align-items: center; 
 
    background: #ccc; 
 
} 
 

 
div { 
 
    width: 150px; 
 
    height: 150px; 
 
    box-sizing: border-box; 
 
    border: solid 25px #afafaf; 
 
    background: orange; 
 
}
<div></div>

2

您是否試圖用圖像創建一個div,並且它的一部分覆蓋了純色?

HTML:

<div> 
<img alt="myImage" src="https://sarasoueidan.com/images/svg-vs-gif--circle-on-transparent-background.svg" /> 
</div> 

CSS:

div { 
    width: 400px; 
    height: 400px; 
    border-style: solid; 
    border-width: 5px; 
} 

div:before{ 
    position:absolute; 
    z-index:-1; 
    top:7%; 
    left:2%; 
    width:45%; 
    height:50%; 
    content:""; 
    background-color:red; 
} 

可能不是最好的方式做到這一點,但很好哦,希望這可以幫助你!

1

您可以添加普通背景,然後在該背景上創建任何顏色的陰影。這仍然會按照常規背景顯示在內容後面。

div { 
 
    height: 300px; 
 
    width: 300px; 
 
    background: red; 
 
    -webkit-box-shadow: inset 0 0 0px 50px white; 
 
    box-shadow: inset 0 0 0px 50px white; 
 
    border: 1px solid black; 
 
}
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam accumsan tellus tellus, vel iaculis ante bibendum quis. Nam molestie dictum libero, venenatis consectetur diam fermentum eget. Cras nulla mauris, vehicula sit amet dui id, hendrerit laoreet 
 
    augue. Suspendisse id tellus nec felis suscipit vehicula. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Proin posuere sem vitae turpis porta, quis sagittis tortor </div>