Как растянуть картинку на весь экран css?
Чтобы растянуть картинку на весь экран с помощью 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.