sanjihan
sanjihan

Reputation: 6046

set background color, but not to the whole background

Is it possible to set background-color to an element (svg in my case), but the size of background is smaller of the actual element?

Lets say you have a div with 300px width and 300px height. I would like to set background color just to an area of 200px x 200px.

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

Why I ask? because my element contains transparency

Upvotes: 2

Views: 1722

Answers (3)

user2230470
user2230470

Reputation:

I'm not sure this will work for an SVG object, but it will work in HTML and CSS. What you can do is set the box-sizing property to border-box, then give the element a border with the same color as the parent element's background-color. In the example below I set the parent's background-color and the child's border-color to different values, so that you have an idea of what's actually happening.

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>

Upvotes: 1

Rishi
Rishi

Reputation: 351

Are you trying to create a div with an image and have a section of it covered with a solid colour?

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

Probably not the best way to do it but oh well, hope this helps you!

Upvotes: 3

Brino
Brino

Reputation: 2502

You can add a normal background, then create a shadow of any color you prefer over that background. This will still display behind content as a regular background would.

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>

Upvotes: 1

Related Questions