Background

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.

Расположение фонового рисунка [background-position]

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

Есть много способов установить значение . Тем
не менее, все они представляют собой набор координат.
Например, значение ‘100px 200px’ располагает фоновый рисунок на 100px слева и на 200px
сверху в окне браузера.

Координаты можно указывать в процентах ширины экрана, в фиксированных
единицах (пикселы, сантиметры, и т. п.), либо вы можете использовать слова top, bottom, center, left
и right. Модель ниже иллюстрирует сказанное:

В таблице дано несколько примеров.

Значение Описание Пример
Рисунок расположен на 2 cm
слева и на 2 cm сверху
Показать пример
Рисунок расположен по
центру и на четверть экрана сверху
Показать пример
Рисунок расположен в
правом верхнем углу страницы
Показать пример

В примере кода фоновое изображение располагается в правом нижнем углу экрана:

Показать пример

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

BACKGROUND-ATTACHMENT

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

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

CSS

.item-1 {
background-attachment: fixed;
background-size: 50%;
background-image: url(‘graham.png’);
background-repeat: no-repeat;
overflow: scroll;
}
.item-2 { background-attachment: local; /* Остальные стили как у .item-1 */ }
.item-3 { background-attachment: scroll; /* Остальные стили как у .item-1 */ }

1
2
3
4
5
6
7
8
9

.item-1 {

background-attachmentfixed;

background-size50%;

background-imageurl(‘graham.png’);

background-repeatno-repeat;

overflowscroll;

}

.item-2 {background-attachmentlocal;/* Остальные стили как у .item-1 */}

.item-3 {background-attachmentscroll;/* Остальные стили как у .item-1 */}

CSS Свойства

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-widthmix-blend-modeobject-fitobject-positionopacityorderoutlineoutline-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-wrapwriting-modez-index

Property Values

Value Description Play it
stretch Default value. The image is stretched to fill the area Play it »
repeat The image is tiled (repeated) to fill the area Play it »
round The image is tiled (repeated) to fill the area. If it does not fill the area with a whole number of tiles, the image is rescaled so it fits Play it »
space The image is tiled (repeated) to fill the area. If it does not fill the area with a whole number of tiles, the extra space is distributed around the tiles
initial Sets this property to its default value. Read about initial Play it »
inherit Inherits this property from its parent element. Read about inherit

Управление позицией фонового изображения

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

Значение Описание
left topleft centerleft bottomright topright centerright bottomcenter topcenter centercenter bottom Задает положение изображения. Первое значение-горизонтальное положение, а второе значение вертикальное. Если вы указываете только одно ключевое слово, другое значение будет «center»
x% y% Задает положение изображения. Первое значение — горизонтальное положение, а второе значение вертикальное. Левый верхний угол имеет 0% 0% (это значение по умолчанию). В правом нижнем углу 100% 100%. Если указано только одно значение, то другое значение будет 50%.
x y Задает положение изображения. Первое значение — горизонтальное положение, а второе значение вертикальное. Левый верхний угол имеет 0 0. Значения могут быть в пикселях, или других единицах измерения CSS. Если указано только одно значение, то другое значение будет 50%. Вы можете совместно использовать проценты и единицы измерения.

Рассмотрим пример использования этого свойства:

<!DOCTYPE html>
<html>
<head>
	<title>Пример позиционирования фонового изображения</title>
<style> 
div {
display: inline-block; /* устанавливаем, что элементы становятся блочно-строчными (чтобы выстроились в линейку) */
background-image: url("smile_bg.png"); /* указываем путь к файлу изображения, которое будет использоваться как задний фон */
background-repeat: no-repeat; /**/
width: 100px; /* устанавливаем ширину элемента */
height: 100px; /* устанавливаем высоту элемента */
border: 1px solid; /* устанваливаем сплошную границу размером 1 пиксель */
margin: 10px; /* устанавливаем внешние отступы со всех сторон */
text-align: center; /* выравниваем текст по центру */
line-height: 60px; /* указываем высоту строки */
background-color: azure; /* задаем цвет заднего фона */
}
.leftTop {background-position: left top;} /* задаем позицию ключевыми словами */
.leftCenter {background-position: left center;} /* задаем позицию ключевыми словами */
.leftBottom {background-position: left bottom;} /* задаем позицию ключевыми словами */
.rightTop {background-position: right top;} /* задаем позицию ключевыми словами */
.rightCenter {background-position: right center;} /* задаем позицию ключевыми словами */
.rightBottom {background-position: right bottom;} /* задаем позицию ключевыми словами */
.centerTop {background-position: center top;} /* задаем позицию ключевыми словами */
.centerCenter {background-position: center center;} /* задаем позицию ключевыми словами */
.centerBottom {background-position: center bottom;} /* задаем позицию ключевыми словами */
.userPosition {background-position: 20px 75%;} /* задаем позицию по горизонтали в пикселях, а по вертикали в процентах */
</style>
</head>
	<body>
		<div class = "leftTop">left top</div>
		<div class = "leftCenter">left center</div>
		<div class = "leftBottom">left bottom</div>
		<div class = "rightTop">right top</div>
		<div class = "rightCenter">right center</div>
		<div class = "rightBottom">right bottom</div>
		<div class = "centerTop">center top</div>
		<div class = "centerCenter">center center</div>
		<div class = "centerBottom">center bottom</div>
		<div class = "userPosition">20px 75%</div>
	</body>
</html>

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

Результат нашего примера:

Рис. 117 Пример позиционирования фонового изображения.

Иконка рядом с текстом

На скриншоте выше видно, что значок находится слева от текста. Вспоминаем все свойства background и понимаем, что для размещения слева годится background-position (начальная позиция фонового изображения). Перейдём к коду.

Сперва ничего особенного — обычная ссылка:

Вся магия в CSS:

  • Сначала задали путь до изображения.
  • Потом установили начальное положение фона (background-position) в left center — ведь наша иконка левее текста (горизонтальная позиция left) и на одном с ним уровне (вертикальная позиция center).
  • Размер фонового изображения (background-size) мы задали, чтобы предотвратить отдалённые проблемы.Дело в том, что иконка может оказаться больше блока, в котором её захотят показать. Тогда она некрасиво обрежется по бокам. Чтобы этого не произошло — указываем размеры, в которые иконка должна вписаться.

И наконец, устанавливаем режим повторения фона (background-repeat) в no-repeat. Без этого фоновая картинка будет дублироваться, пока не заполнит собой блок (как это выглядит — зависит от размеров картинки и html-элемента, где она задана фоном).

Что же мы получили:

Не совсем то, чего ожидали. Давайте разбираться.

Наш «конвертик» стал фоновым изображением для блока, который занимает ссылка. Текст ссылки — это содержимое того же блока. Оно и наложилось на наше фоновое изображение.

Значит, нужно отодвинуть это самое содержимое от левой границы блока (помните, мы прижали «конвертик» именно к левому краю). Причём отодвинуть более чем на 20px (ширина фоновой картинки, заданная background-size) — тогда увидеть наш фон уже ничто не помешает.

Делается это с помощью свойства padding (внутренний отступ).

Добавим в код такой отступ слева:

Вот теперь всё вышло как надо:

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

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

Значение Описание Воспроизвести
repeat Фоновое изображение повторяется как по вертикали, так и по горизонтали. Последнее изображение будет обрезано, если оно не подходит. Это показатель Воспроизвести »
repeat-x Фоновое изображение повторяется только по горизонтали Воспроизвести »
repeat-y Фоновое изображение повторяется только по вертикали Воспроизвести »
no-repeat Фоновое изображение не повторяется. Изображение будет показано только один раз Воспроизвести »
space Фоновое изображение повторяется как можно чаще без отсечения. Первое и последнее изображения закрепляются по обе стороны от элемента, а пробелы равномерно распределяются между изображениями Воспроизвести »
round Фоновое изображение повторяется и сжимается или растягивается, чтобы заполнить пространство (нет пробела) Воспроизвести »
initial Задает этому свойству значение индекса. Прочитать о initial Воспроизвести »
inherit Наследует это свойство от родительского элемента. Прочитать о inherit

BACKGROUND-CLIP

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

CSS

.item-1{
background-image: url(graham.jpg);
background-origin: border-box;
background-clip: border-box;
background-color: grey;
background-repeat: no-repeat;
border: 10px dashed #8e1d21;
padding: 20px;
}
.item-2 { background-clip: padding-box; /* Остальные стили как у .item-1 */ }
.item-3 { background-clip: content-box; /* Остальные стили как у .item-1 */ }

1
2
3
4
5
6
7
8
9
10
11

.item-1{

background-imageurl(graham.jpg);

background-originborder-box;

background-clipborder-box;

background-colorgrey;

background-repeatno-repeat;

border10pxdashed#8e1d21;

padding20px;

}

.item-2 {background-clippadding-box;/* Остальные стили как у .item-1 */}

.item-3 {background-clipcontent-box;/* Остальные стили как у .item-1 */}

Перевод статьи: https://bitsofco.de/the-background-properties/

твиттерефейсбуке

Property Values

Value Description CSS
background-color Specifies the background color to be used 1
background-image Specifies ONE or MORE background images to be used 1
background-position Specifies the position of the background images 1
background-size Specifies the size of the background images 3
background-repeat Specifies how to repeat the background images 1
background-origin Specifies the positioning area of the background images 3
background-clip Specifies the painting area of the background images 3
background-attachment Specifies whether the background images are fixed or scrolls with the rest of the page 1
initial Sets this property to its default value. Read about initial 3
inherit Inherits this property from its parent element. Read about inherit 2

Составное свойство background

Составное свойство — значит состоящее из ряда свойств, перечисленных выше, которые нужно перечислять через пробел в определенном порядке. Хорошо тем, что в одной строке вы сразу рассказываете браузеру обо всех нюансах фона для элемента. Коротко, ясно, понятно. Плохо, что не все редакторы кода при этом выдают свои подсказки при использовании составного свойства.

Записывается так:

Составное свойство background

CSS

background-image || background-position/background-size || background-repeat || background-attachment
|| background-origin || background-clip || background-color

1
2

background-image||background-position/background-size||background-repeat||background-attachment

||background-origin||background-clip||background-color

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

Например, можно указать только цвет фона, используя это свойство:

background: #ccc;

1 background#ccc;

И все — цвет фона будет серым.

Или записать в нем только путь к  фоновому изображению:

background-image: url(img/someimage.jpg);

1 background-imageurl(imgsomeimage.jpg);

Различные сочетания свойств группы background вы найдете в примере ниже. По умолчанию выделен тот пункт, который указан в css-свойствах для блока.

Внимание: обычной ошибкой новичков, да и не только, является следующий подход: хотим вставить сначала только изображение и записываем:

background-image: url(img/someimage.jpg);

1 background-imageurl(imgsomeimage.jpg);

А потом понимаем, что этого недостаточно. Что картинка должно быть одна и размещаться должна справа снизу. Добавляем свойство:

background-image: url(img/someimage.png) no-repeat right bottom;

1 background-imageurl(imgsomeimage.png)no-repeat right bottom;

И — вау — ничего не работает!!! А почему? Да потому, что свойство указано, как , а затем превращено в  . Но браузер-то видит запись !!! И не понимает, почему там так много ненужных слов.

Поэтому нужно быть внимательным при добавлении такого свойства.

Еще одна возможная ошибка заключается в том, что сначала записывается цвет фона, а затем добавляется составное свойство с перечислением всех нюансов размещения картинки, но БЕЗ указания цвета. И в итоге браузер заменяет его на значение по умолчанию, т.е. (прозрачный цвет).

Пример:

background-color: #ccc;
background: url(img/someimage.png) no-repeat right bottom;

1
2

background-color#ccc;

backgroundurl(imgsomeimage.png)no-repeat right bottom;

Property Values

Value Description Play it
left top
left center
left bottom
right top
right center
right bottom
center top
center center
center bottom
If you only specify one keyword, the other value will be «center» Play it »
x% y% The first value is the horizontal position and the second
value is the vertical. The top left corner is 0% 0%.
The right bottom corner is 100% 100%. If you only specify one
value, the other value will be 50%. . Default value is: 0% 0%
Play it »
xpos ypos The first value is the horizontal position and the second
value is the vertical. The top left corner is 0 0. Units can be pixels
(0px 0px) or any other CSS units. If you only specify one value, the other value will be 50%. You can mix % and positions
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

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

Повторение фоновых картинок background-repeat

Свойство предназначено для управления повторением фоновой картинки. Является не наследуемым.

background-repeat
Значения:
При таком параметре фон повторяется многократно во все направлениях. При заданном правиле , повторение фонового имиджа осуществляется с учетом позиции. Является дефолтным
Без повторения.
Повторение слева направо вдоль воображаемой горизонтальной оси координат.
Повторение сверху вниз право вдоль воображаемой вертикальной оси координат.
Переводит в дефолтное состояние.
При выборе этой опции, данное правило будет унаследовано от родителя.

Формат записи

More Examples

Example

Sets two background images for the <body> element. Let the first
image appear only once (with no-repeat), and let the second image be repeated:

body {  background-image: url(«img_tree.gif»), url(«paper.gif»);
 
background-repeat: no-repeat, repeat;  background-color: #cccccc;}

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 */}

Example

Sets a linear-gradient (two colors) as a background image for a <div> element:

#grad1 {  height: 200px;  background-color: #cccccc;  background-image:
linear-gradient(red, yellow);}

Example

Sets a linear-gradient (three colors) as a background image for a <div> element:

#grad1 {  height: 200px;  background-color: #cccccc;  background-image:
linear-gradient(red, yellow, green);}

Example

The repeating-linear-gradient() function is used to repeat linear gradients:

#grad1 {  height: 200px;  background-color: #cccccc;  background-image:
repeating-linear-gradient(red, yellow 10%, green 20%);}

Example

Sets a radial-gradient (two colors) as a background image for a <div> element:

#grad1 {  height: 200px;  background-color: #cccccc;  background-image:
radial-gradient(red, yellow);}

Example

Sets a radial-gradient (three colors) as a background image for a <div> element:

#grad1 {  height: 200px;  background-color: #cccccc;  background-image:
radial-gradient(red, yellow, green);}

Example

The repeating-radial-gradient() function is used to repeat radial gradients:

#grad1 {  height: 200px;  background-color: #cccccc;  background-image:
repeating-radial-gradient(red, yellow 10%, green 20%);}

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

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

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

Adblock
detector