Фон и границы

Написание общих стилей

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

body {
    font-family: 'Open Sans', sans-serif;
    font-size: 1em;
    color: #eee;
    background-color: #383838;
    background-image: url(../img/bg.png);
}
.container {
    width: 100%;
    max-width: 960px;
    margin-left: auto;
    margin-right: auto;
}
a {
    text-decoration: none;
    color: #fff;
}
h1,
h2,
h3 {
    text-transform: uppercase;
}
h2 {
    font-size: 32px;
    text-align: center;
    margin-top: 40px;
    margin-bottom: 40px;
}
img {
    display: block;
    max-width: 100%;
    height: auto;
}
.button,
button {
    border: 0;
    background-image: linear-gradient(145deg, #dd0000, #ff3670);
    color: #fff;
    text-transform: uppercase;
    font-size: 1.2em;
    font-family: 'Open Sans', sans-serif;
    margin-top: 20px;
    margin-bottom: 20px;
    display: inline-block;
}
.button:hover,
button:hover {
    background-image: linear-gradient(145deg, #ff3670, #dd0000);
}

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

Настройки для блока остаются идентичны стилям в предыдущем лендинге.

Стандартный подчеркнутый стиль для ссылок нам не нужен, поэтому мы отключаем его, а также меняем цвет с классического синего на белый. А текст всех заголовков, встречающихся на странице, мы делаем прописными буквами. Заголовкам добавляем отступы сверху и снизу (поскольку стандартные отступы обнулил файл Reset.css), задаем размер шрифта и выравниваем по центру.

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

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

Все остальные свойства CSS вы уже видели много раз, поэтому мы думаем, что вы легко поймете, за что они отвечают в данном коде. Что ж, двигаемся дальше!

Иконка соцсети без текста

Почти на любом сайте есть блок со ссылками на Facebook, «ВКонтакте», Instagram и другие соцсети:

Поскольку это иконки, а текста (контентной составляющей) мы рядом не видим, — нужно использовать CSS.

Здесь есть пара нюансов:

  1. Раз текста нет, то у ссылки нет размеров. А фона без размеров не бывает (нельзя покрасить стену, когда самой стены нет).
  2. Если мы зададим размеры ссылке, то они не сработают, так как по умолчанию ссылка — строчный элемент (его размер не изменить с помощью свойств width и height).

Обойдём эти ограничения.

Сперва напишем простую разметку — список ссылок. Классы сделаем по БЭМ, чтобы наш компонент было удобно стилизовать и использовать повторно.

Начнём, конечно, с HTML-кода:

Далее — CSS:

  • Заметьте, что свойству display для ссылок мы задали значение inline-block. Поэтому наши ссылки стали строчно-блочными элементами. Теперь можно задать им ширину и высоту — и это уже сработает.
  • Одинаковые для всех элементов стили (background-position, background-size, background-repeat) мы вынесли в общий класс social__link.
  • А вот фоновые изображения у нас разные — их мы задаём в разных классах.

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

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

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

Вся магия в CSS:

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

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

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

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

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

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

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

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

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

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

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

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

Существует более простой метод задать значения всех свойств для работы с задним фоном в одном объявлении, используя универсальное свойство background.

Свойство background имеет следующий синтаксис:

background: "color image position/size repeat origin clip attachment;

Где значения соответствуют вышерассмотренным нами свойствам:

  • background-color (color | transparent).
  • background-image (url | none).
  • background-position (значение).
  • background-size (auto | length | cover | contain).
  • background-repeat (repeat | repeat-x |repeat-y | no-repeat).
  • background-origin (padding-box | border-box | content-box).
  • background-clip (border-box | padding-box | content-box).
  • background-attachment (scroll | fixed | local).

Давайте рассмотрим пример использования универсального свойства background:


Пример использования универсального свойства background

И так, что мы сделали в этом примере:

  • Мы установили для элементов <html> и <body> высоту 100%, убрали внутренние и внешние отступы.
  • Для элемента <header> задали минимальную высоту равную 34% от родительского элемента, ширину установили 100%. В качестве заднего фона установили изображение — url(‘cat_g.jpg’), позиционировали его по низу и масштабировали фоновое изображение под размеры элемента (center / contain — background-position / background-size). Без косой черты, как и без позиции фонового изображения работать не будет.
  • Для элемента <div> с классом .primer2 задали минимальную высоту равную 66% от родительского элемента, ширину установили 100%. В качестве заднего фона установили два различных изображения, позиционировали их по центру (center) и масштабировали их (первое изображение полностью помещается — значение contain, второе изображение масштабируется под размеры элемента cover ).

Результат нашей работы:

Рис. 122 Пример использования универсального свойства background.

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

Подробное изучение позиционирования элементов будет освещено далее в учебнике в статье «Позиционирование элементов в CSS».

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

Несколько фоновых изображений

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

div {
  height: 360px;
  width: 400px;
  border: 3px solid #333;
  background: url('../img_flwr.gif') bottom right no-repeat,
              url('../img_tree.gif') repeat-x;
}

Попробовать »

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

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

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

div {
  height: 360px;
  width: 400px;
  border: 3px solid #333;
  background: url('../image.png'),
              url('../img_flwr.gif') bottom right no-repeat,
              url('../img_tree.gif') repeat-x;
}

Попробовать »

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

div {
  height: 360px;
  width: 400px;
  border: 3px solid #333;
  background: url('../img_flwr.gif') bottom right no-repeat,
              url('../img_tree.gif') repeat-x,
			  url('../image.png');
}

Попробовать »

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

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

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

По умолчанию, фоновое изображение позиционируется в верхнем левом углу элемента, используя 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 Пример позиционирования фонового изображения.

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

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

Adblock
detector