background-size
For more information about the supported length units, see the CSS Values and Units Reference.
percentage An integer, followed by a percent (%). A percentage value is relative to the background positioning area.
Examples
Basic list of syntax examples for background-size.
HTML structure of a series of <div> s that are identical except that they have different background-size values applied to the background image.
CSS applied to the HTML example seen above.
Notes
Remarks
An auto value for one dimension is resolved by using the image’s intrinsic ratio and the size of the other dimension. If either of these values is not available, the image’s intrinsic size is used. If the image’s intrinsic size is not available, it is assigned the value of 100%. If both values are auto , use the intrinsic width, height, or both, of the image. If the image has neither an intrinsic width nor an intrinsic height, its size is determined as for contain . Negative values are not allowed. In Windows Internet Explorer 9, the background of a box can have multiple layers. The number of layers is determined by the number of comma-separated values in the background-image property. Each of the images is sized, positioned, and tiled according to the corresponding value in the other background properties (background-attachment, background-clip, background-origin, background-position, background-repeat, and background-size). The first image in the list is the layer closest to the user, the next one is painted behind the first, and so on.
Background-size: масштабирование фонового рисунка
Когда вы добавляете фоновый рисунок через свойство background-image, то по умолчанию изображение отображается в своих реальных размерах. Это не всегда удобно, поэтому в CSS3 появилось новое свойство background-size для регулировки размера фонового изображения.
Значения background-size
Значения для свойства background-size можно задавать при помощи ключевых слов, а также в любых единицах измерения CSS. В одной записи можно указывать размеры как для одной, так и для двух сторон — горизонтальной и вертикальной (последовательность важна).
Ключевые слова
auto (значение по умолчанию) — если данное значение установлено для горизонтали и вертикали, т. е.:
…то размеры фона останутся оригинальными. Если значение auto задано лишь для одной из сторон, то размер фона будет автоматически подогнан под пропорции изображения. Например, если записать следующее:
…то высота фоновой картинки будет вычисляться автоматически.
contain — фоновое изображение масштабируется так, чтобы поместиться внутрь элемента целиком. В зависимости от своей формы и формы элемента, рисунок растягивается, чтобы поместиться полностью либо по ширине, либо по высоте. Пропорции картинки сохраняются.
cover — фоновое изображение масштабируется так, чтобы полностью заполнить пространство элемента, при этом сохраняя свои пропорции. Если пропорции элемента не соответствуют пропорциям изображения, это может привести к тому, что часть рисунка будет скрыта.
Числовые значения
Как мы уже сказали, размер фонового рисунка можно определять с помощью значений, указанных в пикселях, процентах и других единицах измерения CSS.
Чтобы задать точную ширину и высоту, используйте два значения — первое для ширины, второе для высоты:
Учтите, что изображение может исказиться, если вы не попадете в его пропорции:
Чтобы сохранить пропорции фона, используйте для одной из сторон свойство auto :
Здесь высота рисунка составляет 50% от высоты элемента, а ширина подгоняется автоматически
Свойство background-size часто используется на практике. Например, его очень удобно использовать, когда размер элемента указан в процентах. Если задать блоку ширину 50% от ширины экрана, а его фону — ширину 100%, то при изменении размера окна фон всегда будет соответствовать ширине элемента.
Поддержка браузерами
Практически все используемые браузеры (как десктопные, так и мобильные) хорошо работают со свойством background-size. Internet Explorer понимает данное свойство, начиная с 9-й версии.
Далее в учебнике: пишем стиль для фона, используя сокращенную запись — «мульти»-свойство background.
Perfect Full Page Background Image
This post was originally published on August 21, 2009 and is now updated as it has been entirely revised. Both original methods are removed and now replaced by four new methods.
The goal here is a background image on a website that covers the entire browser window at all times. Let’s put some specifics on it:
- Fills entire page with image, no white space
- Scales image as needed
- Retains image proportions (aspect ratio)
- Image is centered on page
- Does not cause scrollbars
- As cross-browser compatible as possible
- Isn’t some fancy shenanigans like Flash
Awesome, easy, progressive CSS way
We can do this purely through CSS thanks to the background-size property now in CSS. We’ll use the html element (better than body as it’s always at least the height of the browser window). We set a fixed and centered background on it, then adjust it’s size using background-size set to the cover keyword.
- 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)
Update: Thanks to Goltzman in the comments for pointing out an Adobe Developer Connection article which features some code to make IE do cover backgrounds as well:
But careful, reader Pierre Orsander said they tried this and had some problems with links on the page going dead.
Update: Matt Litherland writes in to say that anyone trying to use the above IE filters and having problems with scrollbars or dead links or whatever else (like Pierre above) should try not using them on the html or body element. But instead a fixed position div with 100% width and height.
CSS-only technique #1
Big thanks, as usual, to Doug Neiner for this alternate version. Here, we use an inline element, which will be able to resize in any browser. We set a min-height which keeps it filling the browser window vertically, and set a 100% width which keeps it filling horizontally. We also set a min-width of the width of the image so that the image never gets smaller than it actually is.
The especially clever bit is using a media query to check if the browser window is smaller than the image, and using a combo percentage-left and negative left margin to keep it centered regardless.
Here is the CSS:
- Any version of good browsers: Safari / Chrome / Opera / Firefox
- IE 6: Borked – but probably fixable if you use some kind of fixed positioning shim
- IE 7/8: Mostly works, doesn’t center at small sizes but fills screen fine
- IE 9: Works
CSS-only technique #2
One rather simple way to handle this is to put an inline image on the page, fixed position it to the upper-left, and give it a min-width and min-height of 100%, preserving it’s aspect ratio.
However, this doesn’t center the image and that’s a pretty common desire here… So, we can fix that by wrapping the image in a div. That div we’ll make twice as big as the browser window. Then the image will be placed, still preserving it’s aspect ratio and covering the visible browser window, and the dead center of that.
Credit to Corey Worrell for the concept on this one.
- Safari / Chrome / Firefox (didn’t test very far back, but recent versions are fine)
- IE 8+
- Opera (any version) and IE both fail in the same way (wrongly positioned, not sure why)
- Peter VanWylen wrote in to say that if you add the image via JavaScript, the img needs to have width: auto; and height: auto; to work in IE 8, 9, or 10.
Update January 2018: Trying to get this to work on Android? JL García wrote to me saying he needed to add height: 100%; and overflow: hidden; to the html element to get it to work. The full snippet being:
I tested it, and it seemed totally correct. Without it / With it.
This whole idea becomes a lot easier (from a CSS perspective) if we know if the aspect ratio of the image (inline we intend to use as a background) is larger or smaller than the current aspect ratio of the browser window. If it is lower, than we can set only the width to 100% on the image and know it will fill both height and width. If it is higher, we can set only the height to 100% and know that it will fill both the height and width.
We have access to this information through JavaScript. As usual around here, I like to lean on jQuery.
This doesn’t account for centering, but you could definitely alter this to do that. Credits to Koen Haarbosch for the concept behind this idea.
- IE7+ (could probably get in IE6 with a fixed position shim)
- Most any other desktop browser
Update (June 2012): Reader Craig Manley writes in with a technique to load an appropriately sized background image according to screen. As in, don’t load some huge 1900px wide background image for an iPhone.
First, you’d make images like 1024.jpg , 1280.jpg , 1366.jpg , etc. Then, instead of loading an image, you’d load a shim.
If you don’t like the gif shim (personally I think it’s OK because it’s not “content” it’s a background) you could load up one of the real images instead. This code will account for that.
Then you test the screen width and set the src of the image based on it. The code below does it on resize, which you may or may not want. You could just run the code once if you wanted.
Note that screen width isn’t the only possible good information to have when choosing an image size. See this article.
If you use this, please feel free to leave what technique you used and if you altered it in any way in the comments below. Always cool to see techniques “in the wild.”
CSS background-size Свойство
Укажите размер фонового изображения с «Auto» и в пикселях:
#example1 <
background: url(mountain.jpg);
background-repeat: no-repeat;
background-size: auto;
>
#example2 <
background: url(mountain.jpg);
background-repeat: no-repeat;
background-size: 300px 100px;
>
Подробнее примеры ниже.
Определение и использование
Свойство background-size определяет размер фоновых изображений.
С этим свойством можно использовать четыре различных синтаксиса: синтаксис ключевого слова («Auto», «Cover» и «содержит»), синтаксис с одним значением (устанавливает ширину изображения (высота становится «авто»), синтаксис с двумя значениями (первое значение: ширина изображения, второе значение: Height) и синтаксис нескольких фонов (разделенных запятой).
| Значение по умолчанию: | auto |
|---|---|
| Inherited: | no |
| Animatable: | yes. Читайте о animatable |
| Version: | CSS3 |
| Синтаксис JavaScript: | object.style.backgroundSize="60px 120px" |
Поддержка браузера
Номера в таблице указывают первую версию браузера, которая полностью поддерживает свойство.
Номера следуют -webkit-, -moz-, or -o- Укажет первую версию, которая работала с префиксом.
| Свойство | |||||
|---|---|---|---|---|---|
| background-size | 4.0 1.0 -webkit- |
9.0 | 4.0 3.6 -moz- |
4.1 3.0 -webkit- |
10.5 10.0 -o- |
Синтаксис CSS
Значения свойств
| Значение | Описание |
|---|---|
| auto | Значение по умолчанию. Фоновое изображение отображается в исходном размере |
| length | Задает ширину и высоту фонового изображения. Первое значение задает ширину, второе значение задает высоту. Если задано только одно значение, то второй параметр имеет значение «Auto». Читать о единицах длины |
| percentage | Задает ширину и высоту фонового изображения в процентах от родительского элемента. Первое значение задает ширину, второе значение задает высоту. Если задано только одно значение, то второе устанавливается в «Auto» |
| cover | Измените размер фонового изображения, чтобы охватить весь контейнер, даже если он должен растянуть изображение или вырезать немного от одного из краев |
| contain | Измените размер фонового изображения, чтобы убедиться, что изображение полностью отображается |
| initial | Присваивает этому свойству значение по умолчанию. (Читайте о initial) |
| inherit | Наследует это свойство из родительского элемента. (Читайте о inherit) |
Другие примеры
Пример
Укажите размер фонового изображения с процентами:
#example1 <
background: url(mountain.jpg);
background-repeat: no-repeat;
background-size: 100% 100%;
>
#example2 <
background: url(mountain.jpg);
background-repeat: no-repeat;
background-size: 75% 50%;
>
Пример
Укажите размер фонового изображения с помощью «Cover»:
Пример
Укажите размер фонового изображения с «содержать»:
Пример
Здесь у нас есть два фоновых изображения. Мы указываем размер первого фонового изображения с «содержать», а второй фон-изображение с «Cover»: