Перевод не завершен. Пожалуйста, помогите перевести эту статью с английского.
Описание
Значение background-size
в CSS позволяет задавать размер фонового изображения. The size of the image can be fully constrained or only partially in order to preserve its intrinsic ratio.
background
shorthand property that is applied to the element after the background-size
CSS property, the value of this property is then reset to its initial value by the shorthand property.Начальное значение | auto auto |
---|---|
Применяется к | все элементы. Это также применяется к ::first-letter и ::first-line . |
Наследуется | нет |
Проценты | относительно области позиционирования фона |
Отображение | визуальный |
Обработка значения | как указано, но с относительной длиной, конвертируемой в абсолютные длины |
Анимируемость | да, как повторяющийся список из , простой список из , длина, проценты или calc(); когда оба значения являются длинами, они интерполируются как длины; когда оба значения являются процентами, они интерполируются как проценты; в остальных случаях, оба значения преобразуются функцией calc() в сумму длины и процента (каждый из них может быть равен нулю), а затем эта функция интерполирует каждую половину как вещественные числа.. This means keyword values are not animatable. |
Канонический порядок | уникальный неоднозначный порядок, определённый формальной грамматикой |
Синтаксис
/* Ключевые слова */ background-size: cover; background-size: contain; /* Указано одно значение - ширина изображения, */ /* высота в таком случае устанавливается в auto */ background-size: 50%; background-size: 3em; background-size: 12px; background-size: auto; /* Указаны два значения - */ /* ширина и высота соответственно */ background-size: 50% auto; background-size: 3em 25%; background-size: auto 6px; background-size: auto auto; /* Значения для нескольких фонов */ /* Не путайте такую запись с background-size: auto auto */ background-size: auto, auto; background-size: 50%, 25%, 25%; background-size: 6px, auto, contain; /* Глобальные значения */ background-size: inherit; background-size: initial; background-size: unset;
Значения
<размер>
Значение
<length>
, позволяет масштабировать размер фонового изображения в заданном пространстве. Отрицательный размер не допускается.<проценты>
- A
value that scales the background image in the corresponding dimension to the specified percentage of the background positioning area, which is determined by the value of<percentage>
background-origin
. The background positioning area is, by default, the area containing the content of the box and its padding; the area may also be changed to just the content or to the area containing borders, padding, and content. If the background'sattachment
isfixed
, the background positioning area is instead the entire area of the browser window, not including the area covered by scrollbars if they are present. Negative percentages are not allowed. auto
- Значение позволяет изменять размер фонового изображения в соответствии с заданным направлением сохраняя его пропорции.
contain
- A keyword that scales the image as large as possible and maintains image aspect ratio (image doesn't get squished). Image is letterboxed within the container. When the image and container have different dimensions, the empty areas (either top/bottom of left/right) are filled with the background-color. The image is automatically centered unless over-ridden by another property such as background-position.
cover
- A keyword that is the inverse of
contain
. Scales the image as large as possible and maintains image aspect ratio (image doesn't get squished). The image "covers" the entire width or height of the container. When the image and container have different dimensions, the image is clipped either left/right or top/bottom.
The interpretation of possible values depends on the image's intrinsic dimensions (width and height) and intrinsic proportion (ratio of width and height). A bitmap image always has intrinsic dimensions and an intrinsic proportion. A vector image may have both intrinsic dimensions (and thus must have an intrinsic proportion). It also may have one or no intrinsic dimensions, and in either case it might or might not have an intrinsic proportion. Gradients are treated as images with no intrinsic dimensions or intrinsic proportion.
Предупреждение: This behavior changed in Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5). Before this, gradients were treated as images with no intrinsic dimensions, with an intrinsic proportion identical to that of the background positioning area.
Background images generated from elements using -moz-element
(which actually match an element) are currently treated as images with the dimensions of the element, or of the background positioning area if the element is SVG, with the corresponding intrinsic proportion.
The rendered size of the background image is then computed as follows:
Если оба атрибута в background-size
заданы и различны отauto
:- The background image renders at the specified size.
- Если
background-size
содержитcontain
илиcover
: - The image is rendered, preserving its intrinsic proportion, at the largest size contained within, or covering, the background positioning area. If the image has no intrinsic proportion, then it is rendered at the size of the background positioning area.
- Если
background-size
уставновлен какauto
илиauto auto
: - If the image has both intrinsic dimensions, it is rendered at that size. If it has no intrinsic dimensions and no intrinsic proportion, it is rendered at the size of the background positioning area. If it has no dimensions but has a proportion, it's rendered as if
contain
had been specified instead. If the image has one intrinsic dimension and a proportion, it's rendered at the size determined by that one dimension and the proportion. If the image has one intrinsic dimension but no proportion, it's rendered using the intrinsic dimension and the corresponding dimension of the background positioning area. - Если background-size содержит один атрибут
auto
и один не-auto
: - If the image has an intrinsic proportion, then render it using the specified dimension, and compute the other dimension from the specified dimension and the intrinsic proportion. If the image has no intrinsic proportion, use the specified dimension for that dimension. For the other dimension, use the image's corresponding intrinsic dimension if there is one. If there is no such intrinsic dimension, use the corresponding dimension of the background positioning area.
Note that background sizing for vector images that lack intrinsic dimensions or proportion is not yet fully implemented in all browsers. Be careful about relying on the behavior described above, and test in multiple browsers (specifically including versions of Firefox 7 or earlier and Firefox 8 or greater) to be sure different renderings are acceptable.
Формальный синтаксис
<bg-size>#где
<bg-size> = [ <length> | <percentage> | auto ]{1,2} | cover | contain
Примеры
This demonstration of background-size: cover
and this demonstration of background-size: contain
are meant to be opened in new windows so that you can see how contain
and cover
behave when the background positioning area's dimensions vary. This series of demos of how background-size
works and interacts with other background-*
properties should pretty much cover the remaining ground in how to use background-size
alone and in conjunction with other properties.
Замечания
If you are specifying a gradient as background and have specified a background-size
to go with it, it's best not to specify a size that uses a single auto component, or is specified using only a width value (for example, background-size: 50%
). Rendering of gradients in such cases changed in Firefox 8, and at present it is generally inconsistent across browsers, which do not all implement rendering in full accordance with the CSS3 background-size
specification and with the CSS3 Image Values gradient specification.
.bar { width: 50px; height: 100px; background-image: gradient(...); /* Лучше не использовать */ background-size: 25px; background-size: 50%; background-size: auto 50px; background-size: auto 50%; /* Допускается */ background-size: 25px 50px; background-size: 50% 50%; }
Note that it's particularly not recommended to use a pixel dimension and an auto
dimension with a gradient, because it's impossible to replicate rendering in versions of Firefox prior to 8, and in browsers not implementing Firefox 8's rendering, without knowing the exact size of the element whose background is being specified.
Спецификации
Спецификация | Статус | Комментарий |
---|---|---|
CSS Backgrounds and Borders Module Level 3 Определение 'background-size' в этой спецификации. |
Кандидат в рекомендации | Первоначальное определение |
Совместимость с браузерами
Особенность | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) | ||
---|---|---|---|---|---|---|---|
Базовая поддержка | 1.0-webkit [2] | 3.6 (1.9.2)-moz [4] | 9.0 [5] | 9.5-o with some bugs [1] |
3.0 (522)-webkit but from an older CSS3 draft [2] |
||
3.0 | 4.0 (2.0) | 10.0 | 4.1 (532) | ||||
Поддержка значенийcontain и cover |
3.0 | 3.6 (1.9.2) | 9.0 [5] | 10.0 | 4.1 (532) | ||
Поддержка SVG фонов | 44.0 | 8.0 (8.0) | 9.0 | 31.0 | ? |
Особенность | Android | Firefox Mobile (Gecko) | Windows Phone | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
Базовая поддержка | (Да)-webkit 2.3 |
1.0-moz 4.0 |
? | ? | 5.1 (maybe earlier) |
Поддержка SVG фонов | ? | 8.0 (8.0) | ? | ? | ? |
- [1] Opera 9.5's computation of the background positioning area is incorrect for fixed backgrounds. Opera 9.5 also interprets the two-value form as a horizontal scaling factor and, from appearances, a vertical clipping dimension. This has been fixed in Opera 10.
- [2] WebKit-based browsers originally implemented an older draft of CSS3
background-size
in which an omitted second value is treated as duplicating the first value; this draft does not include thecontain
orcover
keywords. - [3] Konqueror 3.5.4 supports
-khtml-background-size
. - [4] While this property is new in Gecko 1.9.2 (Firefox 3.6), it is possible to stretch a image fully over the background in Firefox 3.5 by using
-moz-border-image
..foo { background-image: url(bg-image.png); -webkit-background-size: 100% 100%; /* Safari 3.0 */ -moz-background-size: 100% 100%; /* Gecko 1.9.2 (Firefox 3.6) */ -o-background-size: 100% 100%; /* Opera 9.5 */ background-size: 100% 100%; /* Gecko 2.0 (Firefox 4.0) and other CSS3-compliant browsers */ -moz-border-image: url(bg-image.png) 0; /* Gecko 1.9.1 (Firefox 3.5) */ }
- [5] Хотя Internet Explorer 8 не поддерживает значение
background-size
, с помощью нестандартного атрибута-ms-filter
возможно вопсроизвести некоторые его возможности:-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='path_relative_to_the_HTML_file', sizingMethod='scale')";
This simulates the valuecover
.