Background-size
Содержание:
CSS Reference
CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS Font FallbacksCSS 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
break-after
break-before
break-inside
caption-side
caret-color
@charset
clear
clip
clip-path
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-feature-settings
font-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
font-variant-caps
font-weight
gap
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
row-gap
scroll-behavior
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
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.
Значение свойств
Значение | Описание | Воспроизвести |
---|---|---|
auto | Значение по умолчанию. Фоновое изображение отображается в исходном размере | Воспроизвести » |
length | Задает ширину и высоту фонового изображения. Первое значение задает ширину, второе значение задает высоту. Если задано только одно значение, то второе имеет значение quot;auto». Прочитать Единицы длинЫ | Воспроизвести » |
percentage | Задает ширину и высоту фонового изображения в процентах от родительского элемента. Первое значение задает ширину, второе значение задает высоту. Если задано только одно значение, то второе имеет значение «auto» | Воспроизвести » |
cover | Измените размер фонового изображения, чтобы покрыть весь контейнер, даже если он должен растянуть изображение или немного отрезать один из краев | Воспроизвести » |
contain | Измените размер фонового изображения, чтобы убедиться, что изображение полностью видно | Воспроизвести » |
initial | Задает этому свойству значение индекса. Прочитать о initial | Воспроизвести » |
inherit | Наследует это свойство от родительского элемента. Прочитать о inherit |
CSS Syntax
background: bg-color bg-image position/bg-size bg-repeat bg-origin bg-clip bg-attachment initial|inherit;
Note: If one of the properties in the shorthand declaration is the bg-size property,
you must use a / (slash) to separate it from the bg-position property, e.g. background:url(smiley.gif) 10px 20px/50px 50px;
will result in a background image, positioned 10 pixels from the left, 20 pixels from the top, and the size of the image will be 50 pixels wide and 50 pixels high.
Note: If using multiple background-image sources but also
want a background-color, the background-color parameter needs to be last in the
list.
CSS Properties
align-contentalign-itemsalign-selfallanimationanimation-delayanimation-directionanimation-durationanimation-fill-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-functionbackface-visibilitybackgroundbackground-attachmentbackground-blend-modebackground-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-sizeborderborder-bottomborder-bottom-colorborder-bottom-left-radiusborder-bottom-right-radiusborder-bottom-styleborder-bottom-widthborder-collapseborder-colorborder-imageborder-image-outsetborder-image-repeatborder-image-sliceborder-image-sourceborder-image-widthborder-leftborder-left-colorborder-left-styleborder-left-widthborder-radiusborder-rightborder-right-colorborder-right-styleborder-right-widthborder-spacingborder-styleborder-topborder-top-colorborder-top-left-radiusborder-top-right-radiusborder-top-styleborder-top-widthborder-widthbottombox-decoration-breakbox-shadowbox-sizingbreak-afterbreak-beforebreak-insidecaption-sidecaret-color@charsetclearclipclip-pathcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-feature-settingsfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-variant-capsfont-weightgapgridgrid-areagrid-auto-columnsgrid-auto-flowgrid-auto-rowsgrid-columngrid-column-endgrid-column-gapgrid-column-startgrid-gapgrid-rowgrid-row-endgrid-row-gapgrid-row-startgrid-templategrid-template-areasgrid-template-columnsgrid-template-rowshanging-punctuationheighthyphens@importisolationjustify-content@keyframesleftletter-spacingline-heightlist-stylelist-style-imagelist-style-positionlist-style-typemarginmargin-bottommargin-leftmargin-rightmargin-topmax-heightmax-width@mediamin-heightmin-widthmix-blend-modeobject-fitobject-positionopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerightrow-gapscroll-behaviortab-sizetable-layouttext-aligntext-align-lasttext-decorationtext-decoration-colortext-decoration-linetext-decoration-styletext-indenttext-justifytext-overflowtext-shadowtext-transformtoptransformtransform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functionunicode-bidiuser-selectvertical-alignvisibilitywhite-spacewidthword-breakword-spacingword-wrapwriting-modez-index
More Examples
Example
How to position a background-image to be centered at top:
body
{
background-image: url(‘w3css.gif’);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center top;
}
Example
How to position a background-image to be bottom right:
body
{
background-image: url(‘w3css.gif’);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: bottom right;
}
Example
How to position a background-image using percent:
body
{
background-image: url(‘w3css.gif’);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 50% 50%;
}
Example
How to position a background-image using pixels:
body
{
background-image: url(‘w3css.gif’);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 50px 150px;
}
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 */}
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.
CSS Properties
align-contentalign-itemsalign-selfallanimationanimation-delayanimation-directionanimation-durationanimation-fill-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-functionbackface-visibilitybackgroundbackground-attachmentbackground-blend-modebackground-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-sizeborderborder-bottomborder-bottom-colorborder-bottom-left-radiusborder-bottom-right-radiusborder-bottom-styleborder-bottom-widthborder-collapseborder-colorborder-imageborder-image-outsetborder-image-repeatborder-image-sliceborder-image-sourceborder-image-widthborder-leftborder-left-colorborder-left-styleborder-left-widthborder-radiusborder-rightborder-right-colorborder-right-styleborder-right-widthborder-spacingborder-styleborder-topborder-top-colorborder-top-left-radiusborder-top-right-radiusborder-top-styleborder-top-widthborder-widthbottombox-decoration-breakbox-shadowbox-sizingbreak-afterbreak-beforebreak-insidecaption-sidecaret-color@charsetclearclipclip-pathcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-feature-settingsfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-variant-capsfont-weightgapgridgrid-areagrid-auto-columnsgrid-auto-flowgrid-auto-rowsgrid-columngrid-column-endgrid-column-gapgrid-column-startgrid-gapgrid-rowgrid-row-endgrid-row-gapgrid-row-startgrid-templategrid-template-areasgrid-template-columnsgrid-template-rowshanging-punctuationheighthyphens@importisolationjustify-content@keyframesleftletter-spacingline-heightlist-stylelist-style-imagelist-style-positionlist-style-typemarginmargin-bottommargin-leftmargin-rightmargin-topmax-heightmax-width@mediamin-heightmin-widthmix-blend-modeobject-fitobject-positionopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerightrow-gapscroll-behaviortab-sizetable-layouttext-aligntext-align-lasttext-decorationtext-decoration-colortext-decoration-linetext-decoration-styletext-indenttext-justifytext-overflowtext-shadowtext-transformtoptransformtransform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functionunicode-bidiuser-selectvertical-alignvisibilitywhite-spacewidthword-breakword-spacingword-wrapwriting-modez-index
Способ 0: 100% width/height
Первый способ заключается в использовании значения 100% для одного из параметров тега img – ширины или высоты. При этом второй параметр должен быть установлен в auto для сохранения пропорций изображения. Картинка растянется до размера контейнера по одному из измерений, а второе значение будет рассчитано автоматически. В результате по краям картинки могут образоваться поля, но она поместится в отведённой области целиком, без обрезки.
<html> <head> <style> .wrapper { width: 300px; height: 300px; border: 5px solid #515151; } .exmpl { overflow: hidden; display: flex; justify-content: center; align-items: center; } .exmpl img { height: 100%; width: auto; } </style> </head> <body> <div class="wrapper exmpl"> <img src="/images/braineater.png"> </div> </body> </html>
Так как при высоте 100% от высоты контейнера изображение вылезает за пределы этого контейнера по ширине, для обрезки лишнего используется свойство overflow со значением hidden. При этом, если мы хотим, чтобы в видимую область попала центральная часть изображения, его надо выровнять по центру контейнера. Проще всего это сделать задав контейнеру display: flex, и далее позиционировать изображение по вертикали и горизонтали с помощью свойств justify-content и align-items.
Недостатком такого метода является то, что если часть изображений вытянута горизонтально, а часть вертикально, то одни из них заполнят область целиком, тогда как другие образуют поля.
Чтобы избавиться от полей можно заменить свойства width и height на min-width и min-height (при этом ширина и высота по умолчанию примут значения auto). Тогда вне зависимости от ориентации изображения, оно заполнит область целиком.
Важно: если вы используете выравнивание с помощью flex-контейнера, добавьте flex-shrink: 0, чтобы запретить автоматическое масштабирование изображения.
<style> .wrapper { width: 300px; height: 300px; border: 5px solid #515151; } .exmpl { overflow: hidden; display: flex; justify-content: center; align-items: center; } .exmpl img { min-width: 100%; min-height: 100%; flex-shrink: 0; } </style>
Но хорошо работать это будет в случае, если исходное изображение меньше контейнера или незначительно отличается от него по размеру, так как в данном случае мы только растягиваем изображение при необходимости, но не уменьшаем его, если оно слишком большое.
Подобным образом можно вырезать только часть изображения, увеличивая или уменьшая масштаб изображения и контролируя смещение с помощью свойства margin.
<style> .wrapper { width: 300px; height: 300px; border: 5px solid #515151; } .exmpl { overflow: hidden; } .exmpl img { width: auto; height: 200%; margin: -60px 0 0 -240px; } </style>
CSS Properties
align-contentalign-itemsalign-selfallanimationanimation-delayanimation-directionanimation-durationanimation-fill-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-functionbackface-visibilitybackgroundbackground-attachmentbackground-blend-modebackground-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-sizeborderborder-bottomborder-bottom-colorborder-bottom-left-radiusborder-bottom-right-radiusborder-bottom-styleborder-bottom-widthborder-collapseborder-colorborder-imageborder-image-outsetborder-image-repeatborder-image-sliceborder-image-sourceborder-image-widthborder-leftborder-left-colorborder-left-styleborder-left-widthborder-radiusborder-rightborder-right-colorborder-right-styleborder-right-widthborder-spacingborder-styleborder-topborder-top-colorborder-top-left-radiusborder-top-right-radiusborder-top-styleborder-top-widthborder-widthbottombox-decoration-breakbox-shadowbox-sizingbreak-afterbreak-beforebreak-insidecaption-sidecaret-color@charsetclearclipclip-pathcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-feature-settingsfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-variant-capsfont-weightgapgridgrid-areagrid-auto-columnsgrid-auto-flowgrid-auto-rowsgrid-columngrid-column-endgrid-column-gapgrid-column-startgrid-gapgrid-rowgrid-row-endgrid-row-gapgrid-row-startgrid-templategrid-template-areasgrid-template-columnsgrid-template-rowshanging-punctuationheighthyphens@importisolationjustify-content@keyframesleftletter-spacingline-heightlist-stylelist-style-imagelist-style-positionlist-style-typemarginmargin-bottommargin-leftmargin-rightmargin-topmax-heightmax-width@mediamin-heightmin-widthmix-blend-modeobject-fitobject-positionopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerightrow-gapscroll-behaviortab-sizetable-layouttext-aligntext-align-lasttext-decorationtext-decoration-colortext-decoration-linetext-decoration-styletext-indenttext-justifytext-overflowtext-shadowtext-transformtoptransformtransform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functionunicode-bidiuser-selectvertical-alignvisibilitywhite-spacewidthword-breakword-spacingword-wrapwriting-modez-index
background-size
С помощью свойства можно осуществить изменение величины фоновой картинки, то есть использовать ее масштабирование. Размер можно изменять используя любые единицы, которые допустимы в таблицах CSS – проценты, пиксели, em (величина применяемого в блоке шрифта).
При этом значение пропорционально увеличивает рисунок до ближайших размеров – ширины или высоты, – позволяет полностью заполнить блок, также сохраняя соотношение ширины и высоты.
Значение по умолчанию – .
На примере мы взяли квадрат размером 200×200 и фоновую картинку меньшим размером – 100×100, которой заполнили заполнили всю область фона с помощью .
See the Pen
background-size by Андрей (@adlibi)
on CodePen.