Background-size

Множественные фоны

Таблицы CSS позволяют сделать фон, состоящим из нескольких слоев изображений, количество которых определяется числом значений, вводимых последовательно через запятую после background-image. При этом картинки ложатся друг под друга сверху вниз, начиная с первого. Каждую из них можно определить с помощью указания значений других свойств, имеющих отношение к изображению. Присваивая слою состояние прозрачности, его можно скрывать.

Таким образом, установка значений свойств фона в CSS дает возможность окрасить его в любой цвет, приняв в учет различные элементы блока (свойства и ). Вместо этого или дополнительно внутри элемента можно поместить фоновое изображение, выбрав для него определенное место, увеличив или уменьшив при этом, а также при необходимости повторив его в горизонтальном или/и вертикальном направлении (свойства , , , , , ).

Следует иметь в виду, что рассмотренные свойства не наследуют своих родителей, но цвет фона наследника ввиду его значения по умолчанию, равного , будет таким же, как и родительский. Для наследования свойства необходимо устанавливать его в значение .

Property Values

Value Description Play it
auto Default value. The background image is displayed in its original size Play it »
length Sets the width and height of the background image. The first value sets the width, the second value sets the height. If only one value is given, the second is set to «auto». Read about length units Play it »
percentage Sets the width and height of the background image in percent of the parent element. The first value sets the width, the second value sets the height. If only one value is given, the second is set to «auto» Play it »
cover Resize the background image to cover the entire container, even if it
has to stretch the image or cut a little bit off one of the edges
Play it »
contain Resize the background image to make sure the image is fully visible Play it »
initial Sets this property to its default value. Read about initial Play it »
inherit Inherits this property from its parent element. Read about inherit

The algorithm, in summary

The algorithm can for the most part be summarized by these four rules. There are some edge cases that aren’t covered by these rules, but this covers the majority of cases.

  1. If specifies a fixed dimension (that is, percentages and relative units are fixed by their context), that dimension wins.
  2. If the image has an intrinsic ratio (that is, its width:height ratio is constant, such as 16:9, 4:3, 2.39:1, 1:1, and so forth), the rendered size preserves that ratio.
  3. If the image specifies a size, and the size isn’t modified by constrain or cover, that specified size wins.
  4. If none of the above cases are met, the image is rendered at the same size as the background area.

It’s worth noting that the sizing algorithm only cares about the image’s dimensions and proportions, or lack thereof. An SVG image with fixed dimensions will be treated just like a raster image of the same size.

Note: If you are trying to stretch your SVG to a different aspect ratio with CSS—for example in order to stretch it over the page background—make sure your SVG includes . Find out more about .

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 ❯

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

Property Values

Value Description
url(‘URL‘) The URL to the image. To specify more than one image, separate the URLs with a comma
none No background image will be displayed. This is default
linear-gradient() Sets a linear gradient as the background image. Define at least two
colors (top to bottom)
radial-gradient() Sets a radial gradient as the background image. Define at least two
colors (center to edges)
repeating-linear-gradient() Repeats a linear gradient
repeating-radial-gradient() Repeats a radial gradient
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

Синтаксис

Значение  позволяет масштабировать размер фонового изображения в заданном измерении. Отрицательный размер не допускается.
Значение , которое масштабирует фоновое изображение в соответствующем измерении до указанного процента области расположения фона, которое определяется значением . Область расположения фона по умолчанию является областью, содержащей содержимое поля и его отступы; область также может быть изменена на содержимое или область, содержащую границы, отступы и содержимое. Если фона является , область позиционирования фона вместо этого является всей областью окна браузера, не включая область, покрытую полосами прокрутки, если они присутствуют. Отрицательные проценты не допускаются.
Значение позволяет изменять размер фонового изображения в соответствии с заданным направлением, сохраняя его пропорции.
Масштабирует картинку так, чтобы она максимально накрыла собой весь блок. Картинка при этом не обрезается, а вписывается в блок с сохранением пропорций.
Ключевое слово, обратное . Масштабирует изображение как можно больше c сохранением пропорций изображения (изображение не становится сплющенным). Когда изображение и контейнер имеют разные размеры, изображение обрезается либо влево / вправо, либо сверху / снизу.

Интерпретация возможных значений зависит от внутренних размеров изображений (ширина и высота) и внутренней пропорции (соотношение ширины и высоты). Растровое изображение всегда имеет внутренние размеры и внутреннюю пропорцию. Векторное изображение может иметь оба внутренних размера (и, следовательно, должно иметь внутреннюю пропорцию). Он также может иметь одно или не иметь внутренних размеров, и в любом случае он может иметь или не иметь внутреннюю пропорцию. Градиенты обрабатываются как изображения без внутренних размеров или внутренней пропорции.

Предупреждение: Это поведение изменилось в Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5). До этого, градиенты обрабатывались как изображения без внутренних размеров, с внутренней пропорцией, идентичной пропорции области расположения фона.

Фоновые изображения, сгенерированные из элементов с использованием (en-US) (которые фактически соответствуют элементу) в настоящее время обрабатываются как изображения с размерами элемента, или как область расположения фона, если элементом является SVG, с соответствующей внутренней пропорцией.

Предупреждение: Это не определённое в настоящее время поведение, которое заключается в том, что внутренние размеры и пропорция должны быть такими же как у элемента во всех случаях.

Визуализированный размер фонового изображения затем вычисляется следующим способом:

Если оба атрибута в  заданы и различны от :
Фоновое изображение отображается в указанном размере.
Если  содержит  или :
Изображение визуализируется с сохранением его внутренней пропорции при наибольшем размере, который содержится внутри области размещения фона или покрывает её. Если изображение не имеет внутренней пропорции, оно отображается с размером области расположения фона.
Если  установлен как  или :
Если изображение имеет оба внутренних размера, оно отображается с таким размером. Если оно не имеет внутренних размеров и внутренней пропорции, оно отображается с размером области расположения фона. Если оно не имеет размеров, но имеет пропорцию, оно отображается так, если был был бы указан . Если изображение имеет один внутренний размер и пропорцию, оно отображается с размером, определённым этим одним размером и пропорцией. Если изображение имеет один внутренний размер, но не имеет пропорцию, оно отображается с использованием внутреннего размера и соответствующим размером области позиционирования фона.
Если background-size содержит один атрибут  и один не-:
Если изображение имеет внутреннюю пропорцию, то визуализируйте его используя указанный размер, и вычислите другой размер из указанного размера и внутренней пропорции. Если изображение не имеет внутренней пропорции, используйте указанный размер для этого размера. Для другого размера, используйте соответствующее внутреннее измерение изображения, если оно есть. Если такого внутреннего размера нет, используйте соответствующий размер области расположения фона.

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

где

где

Source image examples

Before diving in to look at the results of using different kinds of source images and seeing how they look when used with , it would be helpful to look at a few example source images that have different dimensions and sizing settings.

In each case, we show what the source image looks like rendered in a 150×150 box, and provide a link to the SVG source.

This image is both dimensionless and proportionless. It doesn’t care what size it is, nor does it care about remaining at a particular aspect ratio. This would make a good gradient desktop background that would work regardless of your screen size and its aspect ratio.

This image specifies a width of 100 pixels but no height or intrinsic ratio. This is, basically, a thin strip of wallpaper that could be stretched across the entire height of a block.

This image specifies a 100 pixel height but no width. It also specifies an intrinsic aspect ratio of 3:4. This ensures that its width:height ratio is always 3:4, unless it’s deliberately scaled to a disproportionate size (that is, by explicitly specifying both width and height that aren’t of that ratio).

This is very much like specifying a specific width and height, since once you have one dimension and a ratio, the other dimension is implied, but it’s still a useful example.

This image doesn’t specify either a width or a height; instead, it specifies an intrinsic ratio of 1:1. Think of this like a program icon. It’s always square, and is usable at any size, such as 32×32, 128×128, or 512×512, for example.

More

Fullscreen VideoModal BoxesDelete ModalTimelineScroll IndicatorProgress BarsSkill BarRange SlidersTooltipsDisplay Element HoverPopupsCollapsibleCalendarHTML IncludesTo Do ListLoadersStar RatingUser RatingOverlay EffectContact ChipsCardsFlip CardProfile CardProduct CardAlertsCalloutNotesLabelsCirclesStyle HRCouponList GroupList Without BulletsResponsive TextCutout TextGlowing TextFixed FooterSticky ElementEqual HeightClearfixResponsive FloatsSnackbarFullscreen WindowScroll DrawingSmooth ScrollGradient Bg ScrollSticky HeaderShrink Header on ScrollPricing TableParallaxAspect RatioResponsive IframesToggle Like/DislikeToggle Hide/ShowToggle Dark ModeToggle TextToggle ClassAdd ClassRemove ClassActive ClassTree ViewRemove PropertyOffline DetectionFind Hidden ElementRedirect WebpageZoom HoverFlip BoxCenter VerticallyCenter Button in DIVTransition on HoverArrowsShapesDownload LinkFull Height ElementBrowser WindowCustom ScrollbarHide ScrollbarShow/Force ScrollbarDevice LookContenteditable BorderPlaceholder ColorText Selection ColorBullet ColorVertical LineDividersAnimate IconsCountdown TimerTypewriterComing Soon PageChat MessagesPopup Chat WindowSplit ScreenTestimonialsSection CounterQuotes SlideshowClosable List ItemsTypical Device BreakpointsDraggable HTML ElementJS Media QueriesSyntax HighlighterJS AnimationsJS String LengthJS ExponentiationJS Default ParametersGet Current URLGet Current Screen SizeGet Iframe Elements

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 ❯

Параметры фонового изображения

Свойство background-image, которое мы только что рассмотрели, может быть дополнено несколькими другими, которые позволяют изменять поведение фонового изображения.

background-attachment: прикрепление фона

Свойство CSS background-attachment используется для «закрепления» фона. Полученный эффект позволяет сделать так, чтобы фон «прокручивался» вместе с текстом. Доступны два значения:

  • fixed: фоновое изображение остается закрепленным;
  • scroll: фоновое изображение прокручивается вместе с текстом (значение по умолчанию).
body
{
background-image: url("snow.png");
background-attachment: fixed; /* Фон остается закрепленным */
}

background-repeat: повторение фона

По умолчанию фоновое изображение повторяется в виде мозаики (таким образом, фон html-страницы распространяется на весь экран). Вы можете изменить это с помощью свойства background-repeat:

  • no-repeat: фон не будет повторяться. Изображение будет размещено на странице в одном экземпляре.
  • repeat-x: изображение будет повторяться только в первой строке, горизонтально.
  • repeat-y: изображение будет повторяться только в первом столбце по вертикали.
  • repeat: фон будет повторяться в виде мозаики (значение по умолчанию).

Пример использования:

body
{
background-image: url("sun.png");
background-repeat: no-repeat;
}

background-position: положение фона

Также можно указать позицию фонового изображения с помощью background-position. Это свойство полезно только в комбинации с background-repeat: no-repeat; (фон, который не повторяется).

Нужно ввести два значения в пикселях, чтобы указать положение фона относительно верхнего левого угла страницы (или абзаца, если вы применяете фон к абзацу). Поэтому, если вы введете:

background-position: 30px 50px;

… фон будет сдвинут на 30 пикселей левее и 50 пикселей выше. Также можно использовать следующие значения:

  • top: вверху;
  • bottom: внизу;
  • left: слева;
  • center: по центру;
  • right: справа.

Их можно комбинировать. Например, чтобы разместить фоновое изображение в правом верхнем углу, нужно ввести:

background-position: top right;

Если я хочу отображать солнце в качестве фонового изображения (следующий рисунок), только один раз (no-repeat), всегда видимым (fixed) и расположенным в правом верхнем углу (top right), то следует написать следующий код фона html-страницы:

body
{
background-image: url("sun.png");
background-attachment: fixed; /* Фон остается  зафиксированным */
background-repeat: no-repeat; /* Фон не будет повторяться */
background-position: top right; /* Фон будет отображаться в правом верхнем углу */
}

Солнце в качестве фонового изображения в правом верхнем углу

Сочетание свойств

Если вы применяете к фону много свойств, то можно использовать своего рода «супер-свойство», называемое background. Его значение может сочетать в себе несколько ранее рассмотренных свойств: background-image, background -repeat, background-attachment и background-position.

Таким образом, можно написать:

body
{
background: url("sun.png") fixed no-repeat top right;
}

Это первое «супер-свойство», которое я вам показываю, но будут и другие. Вы должны знать следующее:

  1. Порядок значений не важен. Можно комбинировать значения в любом порядке.
  2. Не нужно вводить все значения. Поэтому, если не хотите вводить fixed, можно удалить его.

Создание полупрозрачного фона в CSS

Полупрозрачный элемент хорошо заметен на фоновом рисунке. В веб-дизайне полупрозрачность достигается за счёт свойства opacity или задаваемого для фона формата цвета RGBA.

Особенность данного свойства заключается в том, что прозрачность действует не только на фон, но и на все дочерние элементы. После увеличения прозрачности, и текст и фон станут полупрозрачными.

Пример создания полупрозрачного блока:

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>opacity</title>
  <style>
   body {
    background: url("http://cs614726.vk.me/v614726246/4a02/300wj_aFOK4.jpg");
    background-size: 10% auto;
   }
   div {
	 opacity: 0.7;
 	 background: #717ceb; /* Цвет фона */
 	 padding: 20px; /* Поля вокруг текста */
   }
  </style>
 </head>
 <body>
   <div>Так выглядит полупрозрачный блок.</div>
 </body>
</html>

Однако достаточно часто полупрозрачным должен быть только фон определённого элемента, а текст оставаться непрозрачным для читабельности.

В таком случае opacity не подходит и следует воспользоваться форматом RGBA, в котором помимо значений яркости синего, красного и зелёного цветов устанавливается ещё и значение прозрачности. 1 означает абсолютную непрозрачность, а 0 — полную прозрачность.

Пример задания прозрачного фона:

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>rgba</title>
  <style>
   body { 
  background: url("http://cs614726.vk.me/v614726246/4a02/300wj_aFOK4.jpg");
  background-size: 20% auto;
}
   div {
    background: rgba(60, 150, 250, 0.7); /* Цвет фона */
    color: #fff; /* Цвет текста */
    padding: 20px; /* Поля вокруг текста */
   }
  </style>
 </head>
 <body>
  <div>Прозрачный фон блока и непрозрачный текст.</div>
 </body>
</html>

Надеемся, что данное руководство вам пригодилось, и желаем успехов в освоении веб-дизайна!

CSS Advanced

CSS Rounded CornersCSS Border ImagesCSS BackgroundsCSS ColorsCSS Color KeywordsCSS Gradients
Linear Gradients
Radial 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 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

Property Values

Value Description
auto Default value. The background-image contains its width and height
length Sets the width and height of the background image. The first value sets the width, the second value sets the height. If only one value is given, the second is set to «auto»
percentage Sets the width and height of the background image in percent of the parent element. The first value sets the width, the second value sets the height. If only one value is given, the second is set to «auto»
cover Scale the background image to be as large as possible so that the background area is completely covered by the background image. Some parts of the background image may not be in view within the background positioning area
contain Scale the image to the largest size such that both its width and its height can fit inside the content area
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

Вендорные префиксы

Поскольку свойство background-size является довольно новым, старые версии браузеров его могут не поддерживать. Чтобы добиться полной совместимости, необходимо к тому коду еще добавить вендорные префиксы. Пример с сеткой, полностью поддерживаемый старыми браузерами, будет выглядеть так.

body {
    background: linear-gradient(transparent 50%, rgba(186,0,0,0.2) 50%), 
                linear-gradient(90deg, rgba(186,0,0,0.2) 50%, transparent 50%);
    -moz-background-size: 80px 80px; /* Firefox 3.6+ */
    -webkit-background-size: 80px 80px; /* Safari 3.1+ и Chrome 4.0+ */
    -o-background-size: 80px 80px; /* Opera 9.6+ */
    background-size: 80px 80px; /* Современные браузеры */
} 

По-хорошему, градиент в примере тоже надо сделать совместимым со старыми версиями браузеров, поскольку он принадлежит к CSS3. Но в таком случае пример будет избыточным. Просто надо знать, что в градиентах также добавляются вендорные префиксы, чтобы добиться полной совместимости.

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-sizingcaption-sidecaret-color@charsetclearclipcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-weightgridgrid-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-widthobject-fitopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerighttab-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-wrapz-index

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

Пример

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

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

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

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

Adblock
detector