lee A.
lee A.

Reputation: 153

How to force background image to stretch/compress to fit div, without keeping aspect ratio

I've written a script to allow me to resize a div on screen for an application I'm building for a client, but I've run into a humorous issue I've not had before. I know plenty of ways to make sure that an image Does keep its aspect ratio, but I'm not sure of how to force one not to. If, for example, the div is 200px tall and 20px wide, I want it to deform the image to fit that box.

For the application I'm building, this particular image needs to compress/stretch to fit the parent div, regardless of aspect ratio. At the point I'm at right now, I can do this as an image inside of a div tag, or as a background image to the div.

If anyone has any suggestions, I would love to hear them.

Upvotes: 5

Views: 8209

Answers (3)

sol
sol

Reputation: 22949

You can use background-size: 100% 100% for this:

div {
  margin-bottom: 1em;
  width: 300px;
  height: 200px;
  border: 3px solid black;
  background: url(https://openclipart.org/image/800px/350810);
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

div:nth-of-type(2) {
  width: 100px;
  height: 400px;
}

div:nth-of-type(3) {
  width: 500px;
  height: 200px;
}
<div></div>
<div></div>
<div></div>

Upvotes: 4

jaunt
jaunt

Reputation: 5079

Here's a re-sizeable example using background:

div{
  resize:both;
  overflow:hidden;
  width:200px;
  height:300px;
  background:url(https://picsum.photos/200/300)no-repeat 0 0;
  background-size:100% 100%;
}
<div></div>

Here's another using img:

div{
  resize:both;
  overflow:hidden;
  height:300px;
  width:200px;
}
img{
  width:100%;
  height:100%;
}
<div>
  <img src="https://picsum.photos/200/300"/>
</div>

Upvotes: 1

LegendaryJLD
LegendaryJLD

Reputation: 148

In CSS, the background-size property can transform the way the background image proportions itself to the element.

background-size: cover

Edit:

If you want to keep the structure, you can use CSS object-fit properties https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

Upvotes: 0

Related Questions