Background-size: масштабирование фонового рисунка

CSS Справочники

CSS СправочникCSS ПоддержкаCSS СелекторыCSS ФункцииCSS ЗвукCSS Веб шрифтыCSS АнимацииCSS ДлиныCSS Конвертер px-emCSS Названия цветаCSS Значения цветаCSS по умолчаниюCSS Символы

CSS Свойства

align-content
align-items
align-self
all
animation
animation-delay
animation-direction
animation-duration
animation-fill-mode
animation-iteration-count
animation-name
animation-play-state
animation-timing-function
backface-visibility
background
background-attachment
background-blend-mode
background-clip
background-color
background-image
background-origin
background-position
background-repeat
background-size
border
border-bottom
border-bottom-color
border-bottom-left-radius
border-bottom-right-radius
border-bottom-style
border-bottom-width
border-collapse
border-color
border-image
border-image-outset
border-image-repeat
border-image-slice
border-image-source
border-image-width
border-left
border-left-color
border-left-style
border-left-width
border-radius
border-right
border-right-color
border-right-style
border-right-width
border-spacing
border-style
border-top
border-top-color
border-top-left-radius
border-top-right-radius
border-top-style
border-top-width
border-width
bottom
box-decoration-break
box-shadow
box-sizing
caption-side
caret-color
@charset
clear
clip
color
column-count
column-fill
column-gap
column-rule
column-rule-color
column-rule-style
column-rule-width
column-span
column-width
columns
content
counter-increment
counter-reset
cursor
direction
display
empty-cells
filter
flex
flex-basis
flex-direction
flex-flow
flex-grow
flex-shrink
flex-wrap
float
font
@font-face
font-family
font-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
font-weight
grid
grid-area
grid-auto-columns
grid-auto-flow
grid-auto-rows
grid-column
grid-column-end
grid-column-gap
grid-column-start
grid-gap
grid-row
grid-row-end
grid-row-gap
grid-row-start
grid-template
grid-template-areas
grid-template-columns
grid-template-rows
hanging-punctuation
height
hyphens
@import
isolation
justify-content
@keyframes
left
letter-spacing
line-height
list-style
list-style-image
list-style-position
list-style-type
margin
margin-bottom
margin-left
margin-right
margin-top
max-height
max-width
@media
min-height
min-width
mix-blend-mode
object-fit
object-position
opacity
order
outline
outline-color
outline-offset
outline-style
outline-width
overflow
overflow-x
overflow-y
padding
padding-bottom
padding-left
padding-right
padding-top
page-break-after
page-break-before
page-break-inside
perspective
perspective-origin
pointer-events
position
quotes
resize
right
tab-size
table-layout
text-align
text-align-last
text-decoration
text-decoration-color
text-decoration-line
text-decoration-style
text-indent
text-justify
text-overflow
text-shadow
text-transform
top
transform
transform-origin
transform-style
transition
transition-delay
transition-duration
transition-property
transition-timing-function
unicode-bidi
user-select
vertical-align
visibility
white-space
width
word-break
word-spacing
word-wrap
writing-mode
z-index

Images

SlideshowSlideshow GalleryModal ImagesLightboxResponsive Image GridImage GridTab GalleryImage Overlay FadeImage Overlay SlideImage Overlay ZoomImage Overlay TitleImage Overlay IconImage EffectsBlack and White ImageImage TextImage Text BlocksTransparent Image TextFull Page ImageForm on ImageHero ImageBlur Background ImageChange Bg on ScrollSide-by-Side ImagesRounded ImagesAvatar ImagesResponsive ImagesCenter ImagesThumbnailsBorder Around ImageMeet the TeamSticky ImageFlip an ImageShake an ImagePortfolio GalleryPortfolio with FilteringImage ZoomImage Magnifier GlassImage Comparison SliderFavicon

Notas

Se você estiver especificando um gradient como plano de fundo e tiver especificado um  junto, é melhor não especificar um tamanho que use um único componente setado como auto ou seja especificado usando apenas um valor de largura (por exemplo, ).  A renderização de gradients em tais casos mudou no Firefox 8 e, no momento, geralmente é inconsistente em todos os navegadores, pois nem todos implementam a renderização em total conformidade com a especificação do CSS3 e com a .

Observe que, em particular, não é recomendável usar uma dimensão de pixel e uma dimensões  com um gradient, porque é impossível replicar a renderização nas versões do Firefox antes de 8 e nos navegadores que não implementam a renderização do Firefox 8, sem saber o tamanho exato do elemento cujo plano de fundo está sendo especificado.

Possible Values

Here are the possible values:

Specifies that the background image should be scaled, while preserving its intrinsic aspect ratio (if any), to the largest size such that both its width and its height can fit inside the background positioning area.
Specifies that the background image should be scaled, while preserving its intrinsic aspect ratio (if any), to the smallest size such that both its width and its height can completely cover the background positioning area.
<length>

Specifies the size explicitly using a lenth value. For example, will result in a background image being scaled to 300 pixels wide and 100 pixels high.

The first value provided defines the width of the background image. The second value provides the height. If only one value is given, the second becomes .

For example, provides a width of 200 pixels and a height of 50 pixels. A value of will result in the width being 200 pixels and the height being automatically determined by using the image’s intrinsic ratio and the size of the other dimension, or failing that, using the image’s intrinsic size, or failing that, treating it as 100%. In other words, the image should keep its proportions as it scales (i.e. not get distorted).

<percentage>

Specifies the size explicitly using a percentage value. A percentage value is relative to the background positioning area — not to the original image size. For example, will result in a background image being scaled to 70 percent of the background positioning area.

As with the <length> values, the first value provides the width and the second provides the height. If the second value is missing, the height is automatically determined.

Specifies that the image size is automatically determined using the intrinsic width and/or height of the image.

In addition, all CSS properties also accept the following CSS-wide keyword values as the sole component of their property value:

Represents the value specified as the property’s initial value.
Represents the computed value of the property on the element’s parent.
This value acts as either or , depending on whether the property is inherited or not. In other words, it sets all properties to their parent value if they are inheritable or to their initial value if not inheritable.

Другие примеры

Пример

Укажите размер фонового изображения с процентами:

#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»:

#example1 {    background: url(mountain.jpg);   
background-repeat: no-repeat;    background-size: cover;
}

Пример

Укажите размер фонового изображения с «содержать»:

#example1 {    background: url(mountain.jpg);   
background-repeat: no-repeat;    background-size:
contain;}

Пример

Здесь у нас есть два фоновых изображения. Мы указываем размер первого фонового изображения с «содержать», а второй фон-изображение с «Cover»:

#example1 {    background: url(img_tree.gif), url(mountain.jpg);   
background-repeat: no-repeat;    background-size:
contain, cover;}

Определение и использование

Свойство определяет размер фоновых изображений.

Существует четыре различных синтаксиса, которые можно использовать с этим свойством: синтаксис ключевого слова («auto», «cover» и «contain»), синтаксис с одним значением (задает ширину изображения (высота становится «auto»), синтаксис с двумя значениями (первое значение: ширина изображения, второе значение: высота) и множественный синтаксис фона (разделенный запятой).

Значение по умолчанию: auto
Унаследованный: нет
Анимируемый: да. Прочитать о animatable
Редактор кода
Версия: CSS3
JavaScript синтаксис: object.style.backgroundSize=»60px 120px»
Редактор кода

More Examples

Example

Specify the size of a background image with percent:

#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%;}

Example

Specify the size of a background image with «cover»:

#example1 {  background: url(mountain.jpg); 
background-repeat: no-repeat;  background-size: cover;
}

Example

Specify the size of a background image with «contain»:

#example1 {  background: url(mountain.jpg);  background-repeat: no-repeat;
  background-size:
contain;}

Example

Here we have two background images. We specify the size of the first background image with «contain»,
and the second background-image with «cover»:

#example1 {  background: url(img_tree.gif), url(mountain.jpg);
 
background-repeat: no-repeat;  background-size:
contain, cover;}

Example

Use different background properties to create a «hero» image:

.hero-image {  background-image: url(«photographer.jpg»); /* The
image used */  background-color: #cccccc; /* Used if the image is
unavailable */  height: 500px; /* You must set a specified height */ 
background-position: center; /* Center the image */ 
background-repeat: no-repeat; /* Do not repeat the image */ 
background-size: cover; /* Resize the background image to cover the entire container */}

Примеры

Пример

Укажите размер фонового изображения в процентах:

#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»:

#example1 {    background: url(mountain.jpg);   
background-repeat: no-repeat;    background-size: cover;
}

Пример

Укажите размер фонового изображения с помощью «contain»:

#example1 {    background: url(mountain.jpg);   
background-repeat: no-repeat;    background-size:
contain;}

Пример

Здесь у нас есть два фоновых изображения. Мы указываем размер первого фонового изображения с «contain», и второе фоновое изображение с& quot;cover»:

#example1 {    background: url(img_tree.gif), url(mountain.jpg);   
background-repeat: no-repeat;    background-size:
contain, cover;}

Compatibilidad de navegador

We’re converting our compatibility data into a machine-readable JSON format.
This compatibility table still uses the old format,
because we haven’t yet converted the data it contains.
Find out how you can help! (en-US)

Característica Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Soporte Básico 1.0-webkit (en-US) 3.6 (1.9.2)-moz (en-US) 9.0 9.5-o (en-US)
with some bugs
3.0 (522)-webkit (en-US)
but from an older CSS3 draft
   
3.0 4.0 (2.0) 10.0 4.1 (532)
Soporte para y 3.0 3.6 (1.9.2) 9.0 10.0 4.1 (532)
Soporte para SVG backgrounds ? 8.0 (8.0) ? ? ?
Característica Android Firefox Mobile (Gecko) Windows Phone Opera Mobile Safari Mobile
Soporte Básico (Yes)-webkit (en-US)
2.3
? ? ? ?
Soporte para SVG backgrounds ? 8.0 (8.0) ? ? ?

[1  Opera 9.5 ‘s calcula el área de posicionamiento de background es incorrecto para los background fijos. Opera 9,5 también interpreta la forma de dos valores como un factor de escala horizontal y, por las apariencias, una dimensión de recorte vertical. Esto ha sido arreglado en Opera 10.

WebKit-based browsers originally implemented an older draft of CSS3in which an omitted second value is treated as duplicating the first value; this draft does not include theorkeywords.

Los navegadores basados ​​en WebKit- originalmente implementado un proyecto anterior de background-size CSS3 en que se trata de un valor omitido segundo como duplicar el primer valor; este proyecto no incluye el cover o contain palabras claves.

Konqueror 3.5.4 .

Si bien esta propiedad es nueva en Gecko 1.9.2 (Firefox 3.6), es posible estirar una imagen completamente sobre el fondo en Firefox 3.5 usando (en-US).

Спецификации

Specification
Начальное значение
Применяется к все элементы. Это также применяется к и .
Наследуется нет
Проценты относятся к размеру области позиционирования фона минус размер фонового изображения; размер — ширина горизонтальных смещений и высота вертикальных
Обработка значения как и у каждого из подсвойств этого свойства:

  • : Список, каждый элемент которого состоит из: смещения, данного комбинацией абсолютной длины и процентов плюс ключевое слово
  • background-position-y (en-US): Список, каждый элемент которого состоит из: смещения, данного комбинацией абсолютной длины и процентов плюс ключевое слово
Animation type repeatable list of simple list of length, percentage, or calc

Menus

Icon BarMenu IconAccordionTabsVertical TabsTab HeadersFull Page TabsHover TabsTop NavigationResponsive TopnavNavbar with IconsSearch MenuSearch BarFixed SidebarSide NavigationResponsive SidebarFullscreen NavigationOff-Canvas MenuHover Sidenav ButtonsSidebar with IconsHorizontal Scroll MenuVertical MenuBottom NavigationResponsive Bottom NavBottom Border Nav LinksRight Aligned Menu LinksCentered Menu LinkEqual Width Menu LinksFixed MenuSlide Down Bar on ScrollHide Navbar on ScrollShrink Navbar on ScrollSticky NavbarNavbar on ImageHover DropdownsClick DropdownsCascading DropdownDropdown in TopnavDropdown in SidenavResp Navbar DropdownSubnavigation MenuDropupMega MenuMobile MenuCurtain MenuCollapsed SidebarCollapsed SidepanelPaginationBreadcrumbsButton GroupVertical Button GroupSticky Social BarPill NavigationResponsive Header

CSS Background Size

The CSS property allows you to specify the size of background images.

The size can be specified in lengths, percentages, or by using one of the two
keywords: contain or cover.

The following example resizes a background image to much smaller than the original image (using pixels):

Lorem Ipsum Dolor

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Here is the code:

Example

#div1
{
 
background: url(img_flower.jpg);
  background-size: 100px 80px;  background-repeat: no-repeat;
}

The two other possible values for are
and .

The keyword scales the background image to be as large as possible
(but both its width and its height must fit inside the content area). As such, depending on the proportions of the background
image and the background positioning area, there may be some areas of
the background which are not covered by the background image.

The keyword scales the background image so that the content area is
completely covered by the background image (both its width and height are equal to or
exceed the content area). As such, some parts of the background image may not be
visible in the background positioning area.

The following example illustrates the use of and :

Example

#div1
{
 
background: url(img_flower.jpg);
 
background-size: contain;  background-repeat: no-repeat;
}#div2
{
 
background: url(img_flower.jpg);
 
background-size: cover; 
background-repeat: no-repeat;
}

Define Sizes of Multiple Background Images

The property also accepts multiple values for background size
(using a comma-separated list), when working with multiple backgrounds.

The following example has three background images specified, with different
background-size value for each image:

Example

#example1 {  background: url(img_tree.gif) left top
no-repeat
, url(img_flwr.gif) right bottom no-repeat, url(paper.gif) left top
repeat;  background-size: 50px, 130px, auto;}

Full Size Background Image

Now we want to have a background image on a website that covers the entire
browser window at all times.

The requirements are as follows:

  • Fill the entire page with the image (no white space)
  • Scale image as needed
  • Center image on page
  • Do not cause scrollbars

The following example shows how to do it; Use the <html> element
(the <html> element is always at least the height of the browser window). Then set a fixed and centered background on it.
Then adjust its size with the
background-size property:

Example

html {  background: url(img_man.jpg) no-repeat
center fixed;   background-size: cover;}

Hero Image

You could also use different background properties on a <div> to create a hero image (a large image with text), and place it where you want.

Example

.hero-image {  background: url(img_man.jpg) no-repeat center;  
background-size: cover;  height: 500px;  position:
relative;}

CSS background-origin Property

The CSS property specifies where the background image is
positioned.

The property takes three different values:

  • border-box — the background image starts from the upper left corner of the border
  • padding-box — (default) the background image starts from the upper left corner of the padding edge
  • content-box — the background image starts from the upper left corner of the content

The following example illustrates the property:

Example

#example1
{
  border: 10px solid black;  padding: 35px;  background: url(img_flwr.gif);
 
background-repeat: no-repeat; 
background-origin: content-box;}

CSS background-clip Property

The CSS property specifies the painting area of the background.

The property takes three different values:

  • border-box — (default) the background is painted to the outside edge of the border
  • padding-box — the background is painted to the outside edge of the padding
  • content-box — the background is painted within the content box

The following example illustrates the property:

Example

#example1
{
  border: 10px dotted black; 
padding: 35px;  background: yellow; 
background-clip: content-box;}

CSS Advanced Background Properties

Property Description
background A shorthand property for setting all the background properties in one declaration
background-clip Specifies the painting area of the background
background-image Specifies one or more background images for an element
background-origin Specifies where the background image(s) is/are positioned
background-size Specifies the size of the background image(s)

❮ Previous
Next ❯

Замечания

Если вы указываете градиент в качестве фона и указали , который будет использоваться вместе с ним, лучше не указывать размер, который использует единственную автоматическую составную часть, или задаётся с использованием только значения ширины (для примера, ). Рендеринг градиентов в таких случаях изменился в Firefox 8, и в настоящее время он обычно несовместим во всех браузерах, которые не реализуют рендеринг в соответствии с и с .

Обратите внимание, что особенно не рекомендуется использовать размер в пикселях и размер  с градиентом, потому что невозможно воспроизвести рендеринг в версиях Firefox до 8 и в браузерах, не реализующих рендеринг Firefox 8, без знания точного размера элемента, фон которого указывается

CSS Reference

CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities

CSS Properties

align-content
align-items
align-self
all
animation
animation-delay
animation-direction
animation-duration
animation-fill-mode
animation-iteration-count
animation-name
animation-play-state
animation-timing-function
backface-visibility
background
background-attachment
background-blend-mode
background-clip
background-color
background-image
background-origin
background-position
background-repeat
background-size
border
border-bottom
border-bottom-color
border-bottom-left-radius
border-bottom-right-radius
border-bottom-style
border-bottom-width
border-collapse
border-color
border-image
border-image-outset
border-image-repeat
border-image-slice
border-image-source
border-image-width
border-left
border-left-color
border-left-style
border-left-width
border-radius
border-right
border-right-color
border-right-style
border-right-width
border-spacing
border-style
border-top
border-top-color
border-top-left-radius
border-top-right-radius
border-top-style
border-top-width
border-width
bottom
box-decoration-break
box-shadow
box-sizing
caption-side
caret-color
@charset
clear
clip
color
column-count
column-fill
column-gap
column-rule
column-rule-color
column-rule-style
column-rule-width
column-span
column-width
columns
content
counter-increment
counter-reset
cursor
direction
display
empty-cells
filter
flex
flex-basis
flex-direction
flex-flow
flex-grow
flex-shrink
flex-wrap
float
font
@font-face
font-family
font-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
font-weight
grid
grid-area
grid-auto-columns
grid-auto-flow
grid-auto-rows
grid-column
grid-column-end
grid-column-gap
grid-column-start
grid-gap
grid-row
grid-row-end
grid-row-gap
grid-row-start
grid-template
grid-template-areas
grid-template-columns
grid-template-rows
hanging-punctuation
height
hyphens
@import
isolation
justify-content
@keyframes
left
letter-spacing
line-height
list-style
list-style-image
list-style-position
list-style-type
margin
margin-bottom
margin-left
margin-right
margin-top
max-height
max-width
@media
min-height
min-width
object-fit
opacity
order
outline
outline-color
outline-offset
outline-style
outline-width
overflow
overflow-x
overflow-y
padding
padding-bottom
padding-left
padding-right
padding-top
page-break-after
page-break-before
page-break-inside
perspective
perspective-origin
pointer-events
position
quotes
resize
right
tab-size
table-layout
text-align
text-align-last
text-decoration
text-decoration-color
text-decoration-line
text-decoration-style
text-indent
text-justify
text-overflow
text-shadow
text-transform
top
transform
transform-origin
transform-style
transition
transition-delay
transition-duration
transition-property
transition-timing-function
unicode-bidi
user-select
vertical-align
visibility
white-space
width
word-break
word-spacing
word-wrap
z-index

Values

<length>
A value scales the background image to the specified value in the corresponding direction. Negative lengths are not allowed.
<percentage>
A percentage value scales the background image to the specified percentage value relative to the background positioning area, which is determined by the value of the property. Unless the value of the property is set by the author, it has the value of , which means that the background image is positioned with respect to a background coordinate system whose center is at the top left corner of the padding box. Negative percentage values are not allowed.
contain
Scale the image, while preserving its intrinsic aspect ratio (if any), to the largest size such that both its width and its height can fit inside the background positioning area. If the background image has no intrinsic proportion and no intrinsic dimension, then it is rendered at the size of the background positioning area.
cover
Scale the image, while preserving its intrinsic aspect ratio (if any), to the smallest size such that both its width and its height can completely cover the background positioning area. If the background image has no intrinsic proportion and no intrinsic dimension, then it is rendered at the size of the background positioning area.
auto
The keyword that scales the background image in the corresponding direction such that its intrinsic proportion is maintained.

  • If the image has both intrinsic dimensions (height and width), it’s going to be rendered at its size.
  • If the background image has no intrinsic proportion and no intrinsic dimension, then 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 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.

CSS Advanced

CSS Rounded CornersCSS Border ImagesCSS BackgroundsCSS ColorsCSS Color KeywordsCSS Gradients
Linear Gradients
Radial Gradients
Conic Gradients

CSS Shadows
Shadow Effects
Box Shadow

CSS Text EffectsCSS Web FontsCSS 2D TransformsCSS 3D TransformsCSS TransitionsCSS AnimationsCSS TooltipsCSS Style ImagesCSS Image ReflectionCSS object-fitCSS object-positionCSS MaskingCSS ButtonsCSS PaginationCSS Multiple ColumnsCSS User InterfaceCSS Variables
The var() Function
Overriding Variables
Variables and JavaScript
Variables in Media Queries

CSS Box SizingCSS Media QueriesCSS MQ ExamplesCSS Flexbox
CSS Flexbox
CSS Flex Container
CSS Flex Items
CSS Flex Responsive

CSS Tutorial

CSS HOMECSS IntroductionCSS SyntaxCSS SelectorsCSS How ToCSS CommentsCSS Colors
Colors
RGB
HEX
HSL

CSS Backgrounds
Background Color
Background Image
Background Repeat
Background Attachment
Background Shorthand

CSS Borders
Borders
Border Width
Border Color
Border Sides
Border Shorthand
Rounded Borders

CSS Margins
Margins
Margin Collapse

CSS PaddingCSS Height/WidthCSS Box ModelCSS Outline
Outline
Outline Width
Outline Color
Outline Shorthand
Outline Offset

CSS Text
Text Color
Text Alignment
Text Decoration
Text Transformation
Text Spacing
Text Shadow

CSS Fonts
Font Family
Font Web Safe
Font Fallbacks
Font Style
Font Size
Font Google
Font Pairings
Font Shorthand

CSS IconsCSS LinksCSS ListsCSS Tables
Table Borders
Table Size
Table Alignment
Table Style
Table Responsive

CSS DisplayCSS Max-widthCSS PositionCSS Z-indexCSS OverflowCSS Float
Float
Clear
Float Examples

CSS Inline-blockCSS AlignCSS CombinatorsCSS Pseudo-classCSS Pseudo-elementCSS OpacityCSS Navigation Bar
Navbar
Vertical Navbar
Horizontal Navbar

CSS DropdownsCSS Image GalleryCSS Image SpritesCSS Attr SelectorsCSS FormsCSS CountersCSS Website LayoutCSS UnitsCSS SpecificityCSS !importantCSS Math Functions

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

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

Adblock
detector