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!
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.
How do I stretch a background image to cover the entire HTML element?
I’m trying to get a background image of a HTML element (body, div, etc.) to stretch its entire width and height.
Not having much luck. Is it even possible or do I have to do it some other way besides it being a background image?
My current css is:
Edit: I’m not keen on maintaining the CSS in Gabriel’s suggestion so I’m changing the layout of the page instead. But that seems like the best answer so I’m marking it as such.
Как изменить размер фонового изображения с помощью CSS3
Размер фонового изображения может быть изменен и масштабирован. В CSS2.1 фоновые изображения, применяемые к контейнеру, сохраняют свои фиксированные размеры. К счастью CSS3 ввел свойство background-size, которое позволяет растянуть или сжать фон. Оно идеально подходит, если вы используете методы адаптивного веб-дизайна для создания шаблонов.
Здесь можете найти разные методы:
Абсолютное изменение размера
Когда мы устанавливаем фоновое изображение, ширина и высота изображения по умолчанию устанавливаются в «auto», которое сохраняет оригинальный размер изображения. А если необходимо изменить размер изображения, могут быть использованы абсолютные измерения для установления нового размера (px, em, cm и др).
Измерения высоты могут быть применены, используя свойство background-size с абсолютным измерением.
Давайте рассмотрим пример фонового изображения с измененным размером:
Пример
Относительное изменение размера с помощью процентов
Использование процентных значений может быть довольно полезным при адаптивном дизайне. Когда используется процентное значение, размеры основываются на элементе, а не изображении. Если свойство background-size установлено как «100% 100%», фоновое изображение будет растянуто таким образом, чтобы оно заполняло всю область контента.
Пример
Максимальное масштабирование размера
Когда свойство background-size установлено в значение «contain», фоновое изображение будет масштабировано таким образом, чтобы оно заполняло область контента. Но пропорции изображения (отношение высоты и ширины) будут сохранены.
Значение «contain» указывает, что фоновое изображение будет масштабировано независимо от размера контейнера таким образом, что каждая сторона была максимально больше, не переходя длину контейнера с соответствующей стороны.
Другими словами, изображение будет увеличиваться или уменьшаться пропорционально, но размеры контейнера не могут быть больше ширины и высоты.
Пример
Заполнение фоном
Когда свойство background-size установлено в значение «cover», фоновое изображение будет масштабировано таким образом, чтобы оно заполняло всю область контента. Изображение будет масштабировано, чтобы заполнить контентную область, но оно будет обрезано, если соотношения сторон различаются.
Пример
Установление разных фонов для разных устройств
Огромное фото на большом экране будет смотреться идеально, но на экране маленького устройства оно не будет таким эффектным. Тогда зачем загрузить большое фото, если вы все равно должны уменьшить его?
Можно использовать мультимедийные запросы для отображения разных изображений на разных устройствах.
Здесь используется правило @media. В данном примере можно увидеть одно большое изображение и другое поменьше. Они установлены так, чтобы быть отображены по-разному на разных устройствах. Вы увидите результат сами если измените ширину браузера.