天天看點

css禁止背景圖拉伸,CSS:如何強制背景圖像拉伸/壓縮以适應div,而不保持縱橫比...

css禁止背景圖拉伸,CSS:如何強制背景圖像拉伸/壓縮以适應div,而不保持縱橫比...

I'm having a frustrating issue, and would love some help.

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.

解決方案

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

div {

margin-bottom: 1em;

width: 300px;

height: 200px;

border: 3px solid black;

background: url(https://unsplash.it/100x100);

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;

}