Stretch and Scale Background-image with CSS

How to Scale a Background Picture to Fill the Entire Website (or a Column of it) (HTML/CSS)

I was asked by a visitor how he could «stretch a background picture so that it fills the entire screen». This article shows you how to use CSS to resize an image so that it fills either the entire browser window (if your site only has one column) or the entire column (for websites with more than one of them).

Preliminaries

As with all my CSS tutorials, you will need to know a bit of HTML and CSS, otherwise you will have difficulty following what I say below, to say nothing of adapting it to your website. You don’t have to be an expert, but some basic familiarity is needed.

In addition, please note that when I say «background image», I mean that the picture forms the backdrop of a web page, or part of it, with the possibility of some foreground content overlaying it. Such an image is typically placed on a page using the background-image CSS property.

Читайте также:  jQuery Change CSS display Property to none or block

A Few Ways to Scale the Background Image

The CSS property to scale a background image so that it fills all the space available is background-size .

Given that, you still need to figure out what to do if the picture, when expanded, does not fit perfectly into the surrounding space. After all, you can’t expect all your visitors to surf with a browser window opened to a perfect multiple of the dimensions of your image.

An example may make this clearer. Let’s say we want to use thesitewizard.com’s logo as a background image. This is a rectangular picture measuring 202 by 42 pixels. If you were to place it into an enclosure of (say) 300 by 200 pixels and expand it proportionately, it will not scale perfectly to fit into the entire space.

There are at least 3 ways that I can think of to deal with this. Since the question asked is about stretching an image to fill the entire background, I will assume here that you don’t want the browser’s default action of duplicating and tiling your picture across the entire window to fill it. (If you do, you don’t need this article, since the browser does it automatically.)

Preserve Aspect Ratio, No Clipping

If you want the picture to remain undistorted and shown in entirety, one way is to set a CSS rule saying background-size: contain . The result of this is shown below.

#demobox <
background-image: url(../img/logo202x42.png);
background-size: contain ;
background-repeat: no-repeat ;
>

The main rule to note is background-size: contain . It expands the image proportionately so that it is as large as possible in the given enclosing block, yet not so large that any part of the picture exceeds the container. Since the image, when resized in this way, does not cover every bit of blank space, the browser will automatically duplicate it across the remaining area (ie, tile it). If you don’t want this to happen, you can force the browser to only show one copy of the picture with background-repeat: no-repeat , which I did for the above example. You can, if you wish, centre («center» if you use a different variant of English) the picture.

Preserve Aspect Ratio, Clip Overflow

Another way is to proportionately expand the image so big that every part of the container has it as a backdrop, cutting off any portion that overflows the enclosing area.

Stretch to Fill Everything, Ignore Aspect Ratio

If you don’t care whether your picture looks enlongated or squashed, you can force the browser to stretch it along both its axis so that it fills the entire background area.

Compatibility

All current versions of the major browsers support the background-size property. If your visitors use Internet Explorer, they will need at least version 9 to see its effect.

Copyright © 2018 Christopher Heng. All rights reserved.
Get more free tips and articles like this, on web design, promotion, revenue and scripting, from https://www.thesitewizard.com/.

thesitewizard™ News Feed (RSS Site Feed)

Do you find this article useful? You can learn of new articles and scripts that are published on thesitewizard.com by subscribing to the RSS feed. Simply point your RSS feed reader or a browser that supports RSS feeds at https://www.thesitewizard.com/thesitewizard.xml. You can read more about how to subscribe to RSS site feeds from my RSS FAQ.

Please Do Not Reprint This Article

This article is copyrighted. Please do not reproduce or distribute this article in whole or part, in any form.

New Articles

It will appear on your page as:

Copyright © 2018 Christopher Heng. All rights reserved.
thesitewizard™, thefreecountry™ and HowToHaven™ are trademarks of Christopher Heng.
This page was last updated on 20 December 2018.

Источник

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.

HTML

div class="tiledBackground">div> 

CSS

.tiledBackground  background-image: url(https://www.mozilla.org/media/img/logos/firefox/logo-quantum.9c5e96634f92.png); background-size: 150px; width: 300px; height: 300px; border: 2px solid; color: pink; > 

Result

Stretching an image

You can also specify both the horizontal and vertical sizes of the image, like this:

background-size: 300px 150px; 

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:

.square2  background-image: url(favicon.png); background-size: 300px; width: 300px; height: 300px; border: 2px solid; text-shadow: white 0px 0px 2px; font-size: 16px; > 

As you can see, the CSS is actually essentially identical, save the name of the image file.

Special values: «contain» and «cover»

Besides 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.

HTML

div class="bgSizeContain"> p>Try resizing this element!p> div> 

CSS

.bgSizeContain  background-image: url(https://www.mozilla.org/media/img/logos/firefox/logo-quantum.9c5e96634f92.png); background-size: contain; width: 160px; height: 160px; border: 2px solid; color: pink; resize: both; overflow: scroll; > 

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.

HTML

div class="bgSizeCover"> p>Try resizing this element!p> div> 

CSS

.bgSizeCover  background-image: url(https://www.mozilla.org/media/img/logos/firefox/logo-quantum.9c5e96634f92.png); background-size: cover; width: 160px; height: 160px; border: 2px solid; color: pink; resize: both; overflow: scroll; > 

Result

See also

Found a content problem with this page?

This page was last modified on May 24, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Как растянуть и масштабировать фоновое изображение с помощью CSS

Вы можете использовать CSS-свойство background-size: cover; для растягивания и масштабирования фонового изображения. Оно масштабирует изображение как можно больше таким образом, чтобы фоновая область полностью покрывалась фоновым изображением, сохраняя при этом его внутреннее соотношение сторон.

Однако часть изображения может быть не видна (обрезана по вертикали или горизонтали), если ширина или высота измененного фонового изображения слишком велика для элемента.

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

       

Если оно работает не так, как нужно для вас, вы можете попробовать другие значения: background-size: contain; , background-size: 100%; , background-size: 100vw 100vh; и т. д.

kwork banner 480x320 etxt banner 480x320 beget banner 480x320

Читайте также

Похожие примеры:

Источник

Оцените статью