Santhosh
Santhosh

Reputation: 20406

Background image need to fit the div

I have a div the size of which may differ from time to time.

I set a background image with fixed size to that div. But I need to fit the background image to div at any size.

How could be possible through CSS.

Thanks in advance!

Upvotes: 0

Views: 529

Answers (2)

IgalSt
IgalSt

Reputation: 1984

The only way to change a size of an image with CSS is when it's an <img> element. I mean that you can do something like that:

img#myBG { width:200px; height:100px; }

If you need it to be a background, you should use 'z-index' and put your img under a the element that holds the content.

Something like this:

#holder {
  position: relative;
  width: 200px;
  height: 100px;
  border: 1px solid #F00;
}

#holder div {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
}

img#myBG {
  width: 200px;
  height: 100px;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  object-fit: cover;
}
<div id="holder">
  <img id="myBG" src="https://placehold.co/600x400" />
  <div>my content here</div>
</div>

Upvotes: 1

Radomir Dopieralski
Radomir Dopieralski

Reputation: 2585

It's not possible with CSS 2.x that's available in most browsers, but CSS 3 has introduced the background-size property. You can read details here: http://www.css3.info/preview/background-size/

Upvotes: 1

Related Questions