Картинка по размеру блока
Часто возникает необходимость растянуть картинку по размеру блока с сохранением пропорций, чтобы изображение не искажалось. При этом результат бывает нужен разный. Иногда нужно обязательно заполнить всё пространство блока. А иногда важно отобразить всю картинку. Для этого в CSS есть свойство object-fit . Оно может иметь такие значения:
object-fit: fill — картинка просто заполняет блок без сохранения пропорций (по умолчанию)
object-fit: cover — картинка полностью заполняет всё пространство блока. Края изображения могут быть обрезаны из за того, что форма блока не совпадает с формой картинки.
object-fit: contain — вся картинка отображается в блоке. Часть блока может быть не заполнена из за того, что форма блока не совпадает с формой картинки.
object-fit: none — картинка отображается в своём реальном масштабе
object-fit: scale-down — соответствует либо contain либо none . Из этих вариантов выбирает тот, который меньше.
object-fit: initial — возвращает значение по умолчанию, если ранее изображению было установлено другое значение
Как растянуть картинку на весь экран css?

Лучший способ растянуть изображение — это использовать свойство CSS3 background. Вот пример, который использует фоновое изображение для body страницы, рисунок всегда растянется и заполнит весь экран.

Чтобы растянуть картинку на весь экран с помощью CSS, вы можете использовать следующий код:
Этот код устанавливает ширину и высоту картинки равными 100%, что означает, что она будет занимать всю доступную ширину и высоту родительского элемента.
Обратите внимание, что этот код работает только если родительский элемент имеет определенную ширину и высоту. Если это не так, то вы можете использовать следующий код:
Этот код устанавливает ширину и высоту html и body равными 100%, а также убирает верхний и левый отступы (margin), чтобы картинка занимала все доступное пространство.
В этом случае картинка будет растягиваться или уменьшаться в размерах, чтобы соответствовать размерам родительского элемента. Если же вы хотите, чтобы картинка оставалась пропорциональной, но занимала все доступное пространство, можно сделать так:
Этот код устанавливает атрибут object-fit равным cover , что означает, что картинка будет обрезана, чтобы полностью заполнить доступное пространство, но при этом оставаться пропорциональной.
Нужно понимать, что этот код работает только в современных браузерах, поддерживающих атрибут object-fit . Если вы хотите, чтобы ваш код работал во всех браузерах, вы можете использовать JavaScript для реализации такого поведения.
How do you stretch an image to fill a <div> while keeping the image's aspect-ratio?
I need to make this image stretch to the maximum size possible without overflowing it’s <div> or skewing the image.
I can’t predict the aspect-ratio of the image, so there’s no way to know whether to use:
I can’t use both (i.e. style=»width: 100%; height: 100%;») because that will stretch the image to fit the <div> .
The <div> has a size set by percentage of the screen, which is also unpredictable.
![]()
19 Answers 19
Modern browser behave much better. All you should need to do is to set the image width to 100% (demo)
Since you don’t know the aspect ratio, you’ll have to use some scripting. Here is how I would do it with jQuery (demo):
There is a much easier way to do this using only CSS and HTML :
HTML:
CSS:
This will place your image as the background, and stretch it to fit the div size without distortion.
Not a perfect solution, but this CSS might help. The zoom is what makes this code work, and the factor should theoretically be infinite to work ideally for small images — but 2, 4, or 8 works fine in most cases.
![]()
If you’re able to set the image as a background-image then you can do something like this, which will crop the image without stretching it:
If you need to stick with an <img> tag, then as of 2019, you can now use the object-fit css property that accepts the following values:
fill | contain | cover | none | scale-down
As an example, you could have a container that holds an image:
If you can, use background images and set background-size: cover . This will make the background cover the whole element.
If you’re stuck with using inline images there are a few options. First, there is
object-fit
This property acts on images, videos and other objects similar to background-size: cover .
Sadly, browser support is not that great with IE up to version 11 not supporting it at all. The next option uses jQuery
CSS + jQuery
Use the plugin like this
It will take an image, set it as a background image on the image’s wrapper element and remove the img tag from the document. Lastly you could use
Pure CSS
You might use this as a fallback. The image will scale up to cover it’s container but it won’t scale down.
Hope this might help somebody, happy coding!
That’s impossible with just HTML and CSS, or at least wildly exotic and complicated. If you’re willing to throw some javascript in, here’s a solution using jQuery:
That will resize the image so that it will always fit inside the parent element, regardless of it’s size. And as it’s binded to the $(window).resize() event, when user resizes the window, the image will adjust.
This does not try to center the image in the container, that would be possible but I guess that’s not what you’re after.
You can use object-fit: cover; on the parent div.
![]()
Set width and height of the outer container div. Then use below styling on img:
This will help you to keep an aspect ratio of your img
![]()
If you want to set a max width or height (so that it will not be very large) while keeping the images aspect-ratio, you can do this:
![]()
I came across this question searching for a simular problem. I’m making a webpage with responsive design and the width of elements placed on the page is set to a percent of the screen width. The height is set with a vw value.
Since I’m adding posts with PHP and a database backend, pure CSS was out of the question. I did however find the jQuery/javascript solution a bit troblesome, so I came up with a neat (so I think myself at least) solution.
By using style=»» it’s posible to have PHP update my page dynamically and the CSS-styling together with style=»» will end up in a perfectly covered image, scaled to cover the dynamic div-tag.
To make this image stretch to the maximum size possible without overflowing it’s or skewing the image.
styles to the image.
Using this method you can fill in your div with the image varying ratio of divs and images.
jQuery:
HTML:
CSS:
This did the trick for me
if you working with IMG tag, it’s easy.
but i didn’t find how to make it work with #pic < background:url(img/menu.png)>Enyone? Thanks
![]()
I had similar issue. I resolved it with just CSS.
Basically Object-fit: cover helps you achieve the task of maintaining the aspect ratio while positioning an image inside a div.
But the problem was Object-fit: cover was not working in IE and it was taking 100% width and 100% height and aspect ratio was distorted. In other words image zooming effect wasn’t there which I was seeing in chrome.
The approach I took was to position the image inside the container with absolute and then place it right at the centre using the combination:
Once it is in the centre, I give to the image,
This makes the image get the effect of Object-fit:cover.
Here is a demonstration of the above logic.
This logic works in all browsers.
![]()
. And if you want to set or change the image (using #foo as an example):
![]()
Many of the solutions found here have some limitation: some not working in IE ( object-fit) or older browsers, other solutions do not scale up the images (only shrink it), many solution do not support resize of the window and many are not generic, either expect fix resolution or layout(portrait or landscape)
If using javascript and jquery is not a problem I have this solution based on the code of @Tatu Ulmanen. I fixed some issues, and added some code in case the image is loaded dinamically and not available at begining. Basically the idea is to have two different css rules and apply them when required: one when the limitation is the height, so we need to show black bars at the sides, and othe css rule when the limitation is the width, so we need to show black bars at the top/bottom.
Resizing background images with background-size
The background-size CSS property lets you resize the background image of an element, overriding the default behavior of tiling the image at its full size by specifying the width and/or height of the image. By doing so, you can scale the image upward or downward as desired.
Tiling a large image
Let’s consider a large image, a 2982×2808 Firefox logo image. We want (for some reason likely involving horrifyingly bad site design) to tile four copies of this image into a 300×300-pixel element. To do this, we can use a fixed background-size value of 150 pixels.
Result
Stretching an image
You can also specify both the horizontal and vertical sizes of the image, like this:
The result looks like this:
Scaling an image up
On the other end of the spectrum, you can scale an image up in the background. Here we scale a 32×32 pixel favicon to 300×300 pixels:
As you can see, the CSS is actually essentially identical, save the name of the image file.
Special values: «contain» and «cover»
Besides <length> values, the background-size CSS property offers two special size values, contain and cover . Let’s take a look at these.
contain
The contain value specifies that, regardless of the size of the containing box, the background image should be scaled so that each side is as large as possible while not exceeding the length of the corresponding side of the container. Try resizing the example below to see this in action.
Result
cover
The cover value specifies that the background image should be sized so that it is as small as possible while ensuring that both dimensions are greater than or equal to the corresponding size of the container. Try resizing the example below to see this in action.