Как растянуть фон в html
Перейти к содержимому

Как растянуть фон в html

  • автор:

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.


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.


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.



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.

Stretch and scale CSS background

Is there a way to get a background in CSS to stretch or scale to fill its container?

Peter Mortensen's user avatar

16 Answers 16

Use the CSS 3 property background-size :

This is available for modern browsers, since 2012.

vinyll's user avatar

For modern browsers, you can accomplish this by using background-size :

cover means stretching the image either vertically or horizontally so it never tiles/repeats.

That would work for Safari 3 (or later), Chrome, Opera 10+, Firefox 3.6+, and Internet Explorer 9 (or later).

For it to work with lower verions of Internet Explorer, try these CSS:

Scaling an image with CSS is not quite possible, but a similar effect can be achieved in the following manner, though.

Use this markup:

with the following CSS:

and you should be done!

In order to scale the image to be «full bleed» and maintain the aspect ratio, you can do this instead:


It works out quite nicely! If one dimension is cropped, however, it will be cropped on only one side of the image, rather than being evenly cropped on both sides (and centered). I’ve tested it in Firefox, Webkit, and Internet Explorer 8.

EDIT: Modernizr supports detection of background-size support. You can use a JavaScript workaround written to work however you need it and load it dynamically when there is no support. This will keep the code maintainable without resorting to intrusive CSS hacks for certain browsers.

Personally I use a script to deal with it using jQuery, its an adaption of imgsizer. As most designs I do now use width %’s for fluid layouts across devices there is a slight adaptation to one of the loops (accounting for sizes that aren’t always 100%):

EDIT: You may also be interested in jQuery CSS3 Finaliz[s]e.

Try the article background-size. If you use all of the following, it will work in most browsers except Internet Explorer.

Sergio's user avatar

  • Safari 3+
  • Chrome Whatever+
  • IE 9+
  • Opera 10+ (Opera 9.5 supported background-size but not the keywords)
  • Firefox 3.6+ (Firefox 4 supports non-vendor prefixed version)

In addition you can try this for an ie solution

Blowsie's user avatar

Not currently. It will be available in CSS 3, but it will take some time until it’s implemented in most browsers.

Eran Galperin's user avatar

In one word: no. The only way to stretch an image is with the <img> tag. You’ll have to be creative.

This used to be true in 2008, when the answer was written. Today modern browsers support background-size which solves this problem. Beware that IE8 doesn’t support it.

Vilx-'s user avatar

Define «stretch and scale».

If you’ve got a bitmap format, it’s generally not great (graphically speaking) to stretch it and pull it about. You can use repeatable patterns to give the illusion of the same effect. For instance if you have a gradient that gets lighter towards the bottom of the page, then you would use a graphic that’s a single pixel wide and the same height as your container (or preferably larger to account for scaling) and then tile it across the page. Likewise, if the gradient ran across the page, it would be one pixel high and wider than your container and repeated down the page.

Normally to give the illusion of it stretching to fill the container when the container grows or shrinks, you make the image larger than the container. Any overlap would not be displayed outside the bounds of the container.

If you want an effect that relies on something like a box with curved edges, then you would stick the left side of your box to the left side of your container with enough overlap that (within reason) no matter how large the container, it never runs out of background and then you layer an image of the right side of the box with curved edges and position it on the right of the container. Thus as the container shrinks or grows, the curved box effect appears to shrink or grow with it — it doesn’t in fact, but it gives the illusion that is what’s happening.

As for really making the image shrink and grow with the container, you would need to use some layering tricks to make the image appear to function as a background and some javascript to resize it with the container. There’s no current way of doing this with CSS.

If you’re using vector graphics, you’re way outside my realm of expertise I’m afraid.

CSS Background Image Size Tutorial – How to Code a Full Page Background Image

CSS Background Image Size Tutorial – How to Code a Full Page Background Image

This tutorial will show you a simple way to code a full page background image using CSS. And you’ll also learn how to make that image responsive to your users’ screen size.

Making a background image fully stretch out to cover the entire browser viewport is a common task in web design. Fortunately, this task can be taken care of with a few lines of CSS.

Cover Viewport with Image

First, we will want to make sure our page actually covers the entire viewport:

Inside html , we will use the background-image property to set the image:

Magic of ‘Background-Size’ Property

The magic happens with the background-size property:

cover tells the browser to make sure the image always covers the entire container, in this case html . The browser will cover the container even if it has to stretch the image or cut a little bit off the edges.

Because the browser may stretch the image, you should use a background image that has high enough resolution. Otherwise the image may appear pixelated.

If you care about having all of the image appear in the background, then you will want to make sure the image is relatively close in aspect ratio compared to the screen size.

How to Fine Tune an Image Position and Avoid Tiling

The browser can also choose to display your background image as tiles depending on its size. To prevent this from happening, use no-repeat :

To keep things pretty, we will keep our image always centered:

This will center the image both horizontally and vertically at all times.

We have now produced a fully responsive image that will always cover the entire background:

How to Fix an Image in Place When Scrolling

Now, just in case you want to add text on top of the background image and that text overflows the current viewport, you may wish to make sure your image stay in the background when the user scrolls down to see the rest of the text:

You can include all of the background properties described above using short notation:

Optional: How to Add a Media Query for Mobile

To add some icing on the cake, you may wish to add a media query for smaller screens:

You can use Photoshop or some other image editing software to downsize your original image to improve page load speed on mobile internet connections.

So now that you know the magic of creating a responsive, full page image background, it is time to go create some beautiful websites!

Как растянуть картинку на весь экран css?

Аватар пользователя Сергей Мишинs

Чтобы растянуть картинку на весь экран с помощью CSS, вы можете использовать следующий код:

Этот код устанавливает ширину и высоту картинки равными 100%, что означает, что она будет занимать всю доступную ширину и высоту родительского элемента.

Обратите внимание, что этот код работает только если родительский элемент имеет определенную ширину и высоту. Если это не так, то вы можете использовать следующий код:

Этот код устанавливает ширину и высоту html и body равными 100%, а также убирает верхний и левый отступы (margin), чтобы картинка занимала все доступное пространство.

В этом случае картинка будет растягиваться или уменьшаться в размерах, чтобы соответствовать размерам родительского элемента. Если же вы хотите, чтобы картинка оставалась пропорциональной, но занимала все доступное пространство, можно сделать так:

Этот код устанавливает атрибут object-fit равным cover , что означает, что картинка будет обрезана, чтобы полностью заполнить доступное пространство, но при этом оставаться пропорциональной.

Нужно понимать, что этот код работает только в современных браузерах, поддерживающих атрибут object-fit . Если вы хотите, чтобы ваш код работал во всех браузерах, вы можете использовать JavaScript для реализации такого поведения.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *