Daniel Holler
Daniel Holler

Reputation: 245

Have an alternate background if the background image doesnt load

I currently have an image that covers some screen resolutions, but if the screen resolution is bigger than the image, it will be white for each pixel its bigger, so instead of that ugly white, I want a color behind that background image so it wont look ugly. My current code is just an img tag for the background and the css scales it up to 100% but if the screen res is larger than the image res, it will create problems.

Upvotes: 1

Views: 3956

Answers (2)

Aaron Lavers
Aaron Lavers

Reputation: 986

Is there a specific reason why you're using an img tag as your background image, instead of setting a div to have it's background as that image? Because you can do this with css fairly easily.

.background-div {
  width: 100%;
  height: 100%;
  background: url(your_image_url) no-repeat;
  background-size: cover;
  background-color: #e3e3e3;
}

Where the .background-div would be in place of your img... This could also be the body of the document, or whatever. It's just a container div that covers the whole background.

The background then has a fallback colour of #e3e3e3, and background-size: cover means that it will always scale the image to fill the screen, so you won't see that colour. You could also use contain instead, which would make the image scale how you're expecting, and show the background colour where the image doesn't reach.

Upvotes: 2

Red
Red

Reputation: 7299

Find the parent div of your image and add a stylesheet attribute.

It will look something like this

<div class="parent" style="background-color: #000000;height: 100%;width: 100%;">
<img src="your image url" class="image" alt="alt" title="your title"/>
</div>

the attr style="background-color: #000000;" will give the div a black background color.

You can also set the background color by its classname insde you style.css file. Or what ever you named the file.

.parent {
     background: #000;
     height: 100%;
     width: 100%;
}

.parent img {
     max-width: 100%;
}

I hope this is the awnser your searching for. If not, provide some more details. Maybe show the structure of your current code.

Upvotes: 0

Related Questions