Урок 3: цвет и фон

Алан-э-Дейл       01.03.2024 г.

The CSS background- properties

There are several CSS properties used for setting the background of an element. These can be used on to set the background of an entire page.

Setting a

The most straightforward way to change the default (white) background for a page is to use on the body.

One thing you have to watch out for, though — if you set the too dark, the default black text won’t be readable, so you’ll need to change it (or not make the background so dark). See our tutorial on dark backgrounds for more tips on dark-background site design.

Setting a

All of the other CSS properties are connected with setting an image.

  • — The source URL for the image.
  • — Whether and how the image should tile.
  • — Whether and how the image should scroll with the content.
  • — How the image should be placed relative to the element.

The property needs to be a URL to the image. This usually looks like this:

When using the value, you have three choices:

  • relative path based on the root domain of the CSS file — begin with a slash () as shown above
  • relative path based on the immediate directory of the CSS file — no slash ( )
  • absolute URL, if you are linking to an external resource —

Remember that the relative URLs are relative to the CSS file, not the page.

This property specifies whether and how the image will repeat, or tile. The default is for the image to repeat both horizontally and vertically. You can change this by specifying a value other than .

  • — The default. Repeats in both directions.
  • — Repeats only on the x-axis (horizontally across the element).
  • — Repeats only on the y-axis (vertically down the element).
  • — Does not repeat.

This property affects how the background image responds to scrolling.

  • — The background is fixed relative to the viewport (browser window). Scrolling the contents of the element or scrolling the contents of the entire page will not cause the image to move.
  • — The background is fixed relative to the boundaries of the element’s box. Scrolling the entire page (moving the placement of the element itself) will cause the image to move with the element.
  • — The background is fixed relative to the contents of the image. If the contents of the image are scrolled, the background will scroll with them. If the document as a whole is scrolled (causing the element content to be moved), the image will move with the element.

This is a little hard to visualize, so you may want to see this example of all three attachment values, side-by-side. Note that in the context of the element, and will have the same effect.

There are several ways to specify the position of a background image, but the easiest is to use the positioning keywords , , , , and . This gives you nine possibilities:

You can omit if you like, as it is the default value — but it’s a good idea to include for clarity’s sake.

The shorthand property

You can combine all of these rules into a single line labelled .

When using the shorthand property, you can omit any of the components if you just want the default value. You must keep them in the same order, though. Note that you should almost always include a background color, even if you want to have a background fully-covered by an image tile. Especially if the image is dark, you’ll want a color that closely matches the overall color of the image. That way, if the image load fails (or is slow), the text is still readable as intended.

Adam Wood

BACKGROUND-ORIGIN

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

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

CSS

.item-1 {
background-origin: border-box;
background-size: 50%;
background-image: url(‘graham.png’);
background-repeat: no-repeat;
background-position: top left;
border: 10px dashed #8e1d21;
padding: 20px;
}
.item-2 { background-origin: padding-box; /* Остальные стили как у .item-1 */ }
.item-3 { background-origin: content-box; /* Остальные стили как у .item-1 */ }

1
2
3
4
5
6
7
8
9
10
11

.item-1 {

background-originborder-box;

background-size50%;

background-imageurl(‘graham.png’);

background-repeatno-repeat;

background-positiontopleft;

border10pxdashed#8e1d21;

padding20px;

}

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

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

Gradients

Gradients can be used on their own or on top of an existing background color or image.

There are 2 types of gradients:

  1. Linear gradients
  2. Radial gradients

Both gradient types have stops (or points) along the gradient where colors fade from one to another.

Linear gradient

A linear gradient creates a gradient of color in one direction, directed by the angle. To adjust the angle of the gradient, you can:

  1. Click and drag the dot on the direction dial, clicking anywhere on the dial to set the angle position
  2. Click the arrows to rotate the angle in 45-degree increments
  3. Enter the desired angle in the input field

Gradient stops

With gradient stops, you can edit the color and opacity of the gradient by choosing the gradient stops from the gradient bar. If there’s a background image layer underneath the gradient, it will become visible once the opacity is lowered.

To add additional colors to the gradient, add a stop to the gradient bar. You can add more than one stop by clicking anywhere on the gradient bar.

You can adjust the stop positions by clicking and dragging along the gradient bar. 

To delete a stop: 

  1. Long click on the stop
  2. Drag the stop out of the gradient bar until the edges of the stop become transparent 
  3. Let go to remove the stop
Repeat

Toggling Repeat will cause the position and angle of the existing gradient to repeat. 

This is set by the position of the first and last stops. To create a more obvious repeating gradient, drag the first or last stop away from the edge of the gradient bar.

Reverse

The reverse icon reverses the position of the stops.

Radial gradient

Radial gradients create a gradient in the shape of a circle. 

The color stop on the left will be the color you see in the center of the radial gradient.

Position

You can choose the focal point of the gradient, by clicking one of the dots in the position control. For example, click the center dot to justify your image content.

You can also manually adjust the positioning by typing values for the horizontal position (left) and the vertical position (top). You can also change the unit of the values between the px, % (default), vw, and vh.

  • Closest side: the gradient starts from the center point to the closest side
  • Closest corner: the gradient starts from the center point to the closest corner
  • Farthest side: the gradient starts from the center point and continues until it reaches the farthest side
  • Farthest corner: the default preset. The gradient starts from the center point and continues until it reaches the farthest corner

CSS background-image — фоновая картинка на сайте

Свойство CSS background-image — позволяет установить фоновое изображение на сайте.

Синтаксис CSS background-image

Например, для установки общего (глобального) фона:

Например фоновая картинка:

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

В CSS3 можно задать несколько фоновых изображений (они как бы накладываются друг на друга как слои).

Задавая фон в виде картинки есть возможность настраивать так же ряд важных свойств CSS

  • background-repeat
  • background-attachment
  • background-position
  • background-size
  • background-clip

Рассмотрим в отдельности эти параметры

4.1. CSS background-repeat

Свойство CSS background-repeat определяет повторять ли фон. Можно отдельно настраивать повторение по вертикали и горизонтали.

Синтаксис CSS background-repeat

Где value может принимать следующие значения:

  • repeat-x — повторять фоновое изображение по горизонтали;
  • repeat-y — повторять фоновое изображение по вертикали;
  • no-repeat — не повторять фоновое изображение;
  • repeat (по умолчанию) — повторять фоновое изображение по горизонтали и вертикали;
  • space — все пространство заполняется максимально возможным количеством изображений, первое и последнее (по горизонтали и вертикали) поровну обрезаются;
  • round — аналогично предыдущему, с тем отличием, что первое и последнее масштабируются для заполнения;

Например, по горизонтали не повторять, по вертикали повторять фоновое изображение:

4.2. CSS background-attachment

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

Синтаксис CSS background-attachment

Где value может принимать следующие значения:

  • scroll (действует по умолчанию) — фон прокручивается вместе с сайтом;
  • fixed — при прокрутке скролла фон остается неизменными;
  • local — изображение прокручивается с контентом, но не с элементом, его содержащим;

Я думаю, что Вы видели такие сайты и понимаете о чем идет речь.

4.3. CSS background-position

Свойство CSS background-position задает расположение фона относительно левого верхнего угла.

Синтаксис CSS background-position

В параметрах мы указываем выравнивание (смещение) в пикселях или процентах сначала по оси Х, потом по оси У. value, value2 может принимать следующие значения:

  • top — выравнивание по верхнему краю;
  • left — выравнивание с левого края;
  • right — выравнивание с правого края;
  • bottom — выравнивание по нижнему краю;
  • center — выравнивание по центру;
  • число/проценты — можно задавать отступ в виде числа или процентов;

По умолчанию фон располагается в верхнем левом углу.

Можно указывать в пикселях Npx задание отступа от разных краев. Проще понять это на примере:

Фон будет выравнивать по правому краю со смещением 50 пикселей вниз.

Или например сместим фон на 100px вправо и расположим его по центру относительно высоты.

Все эти параметры можно задать в таблице стилей CSS. Этот параметр выравнивает расположение фона на странице.

4.4. CSS background-size

Свойство CSS background-size позволяет задавать размеры фона.

Синтаксис CSS background-size

Где первый параметр задает значение по оси Х, второй параметр по оси У. Можно задавать как в процентах, так и пикселях.

Так же может принимать два статичных параметра

  • contain — масштабирует изображение по длинной стороне (заполняет все пространство)
  • cover — масштабирует изображение по короткой стороне (заполняет все пространство)

Напоследок запишем все атрибуты вместе:

Для обращения к float из JavaScript нужно писать следующую конструкцию:

Вертикальное центрирование

CSS уровня 2 не обладает свойством вертикального центрирования. Вероятно, оно появится в версии CSS уровня 3 (см. ). Но даже в CSS2 вы можете центрировать блоки вертикально при помощи комбинирования нескольких свойств. Хитрость заключается в том, чтобы указать, что внешний блок должен быть отформатирован как ячейка таблицы, т.к. содержимое ячейки таблицы
может быть выровнено по центру вертикально.

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

DIV.container {
    min-height: 10em;
    display: table-cell;
    vertical-align: middle }
...
<DIV class="container">
  <P>Этот маленький абзац...
</DIV>

Способ 0: 100% width/height

Первый способ заключается в использовании значения 100% для одного из параметров тега img – ширины или высоты. При этом второй параметр должен быть установлен в auto для сохранения пропорций изображения. Картинка растянется до размера контейнера по одному из измерений, а второе значение будет рассчитано автоматически. В результате по краям картинки могут образоваться поля, но она поместится в отведённой области целиком, без обрезки.

<html>
  <head>
    <style>
      .wrapper {
        width: 300px;
        height: 300px;
        border: 5px solid #515151;
      }
      .exmpl {
        overflow: hidden;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .exmpl img {
        height: 100%;
        width: auto;
      }
    </style>
  </head>

  <body>
    <div class="wrapper exmpl">
      <img src="/images/braineater.png">
    </div>
  </body>
</html>

Так как при высоте 100% от высоты контейнера изображение вылезает за пределы этого контейнера по ширине, для обрезки лишнего используется свойство overflow со значением hidden. При этом, если мы хотим, чтобы в видимую область попала центральная часть изображения, его надо выровнять по центру контейнера. Проще всего это сделать задав контейнеру display: flex, и далее позиционировать изображение по вертикали и горизонтали с помощью свойств justify-content и align-items.

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

Чтобы избавиться от полей можно заменить свойства width и height на min-width и min-height (при этом ширина и высота по умолчанию примут значения auto). Тогда вне зависимости от ориентации изображения, оно заполнит область целиком.

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

<style>
  .wrapper {
    width: 300px;
    height: 300px;
    border: 5px solid #515151;
  }
  .exmpl {
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .exmpl img {
    min-width: 100%;
    min-height: 100%;
    flex-shrink: 0;
  }
</style>

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

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

<style>
  .wrapper {
    width: 300px;
    height: 300px;
    border: 5px solid #515151;
  }
  .exmpl {
    overflow: hidden;
  }
  .exmpl img {
    width: auto;
    height: 200%;
    margin: -60px 0 0 -240px;
  }
</style>

Сокращенная запись

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

body {
background-image: url("image.png");
background-position: top left;
background-size: 95% 95%;
background-repeat: no-repeat;
background-attachment: scroll;
background-origin: padding-box;
background-clip: content-box;
background-color: #333};
}

Или краткий вариант записи:

body {background: url("image.png") top left / 95% 95% no-repeat scroll padding-box content-box #333;}

Они идентичны, но второй вариант занимает намного меньше места и грузится быстрее.

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.

More Examples

Example

How to position a background-image to be centered at top:

body
{
  background-image: url(‘w3css.gif’);
 
background-repeat: no-repeat;
  background-attachment: fixed;
 
background-position: center top;
}

Example

How to position a background-image to be bottom right:

body
{
 
background-image: url(‘w3css.gif’);
 
background-repeat: no-repeat;
 
background-attachment: fixed;
 
background-position: bottom right;
}

Example

How to position a background-image using percent:

body
{
  background-image: url(‘w3css.gif’);
 
background-repeat: no-repeat;
 
background-attachment: fixed;
 
background-position: 50% 50%;
}

Example

How to position a background-image using pixels:

body
{
  background-image: url(‘w3css.gif’);
 
background-repeat: no-repeat;
 
background-attachment: fixed;
  background-position: 50px 150px;
}

Example

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

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

Тень от изображения.

Чтобы создать эффект тени, используется свойство box-shadow.

Первое значение —  это сдвиг тени по оси X.

Второе значение – это сдвиг тени по оси Y.

Третье значение – размытие тени. Если этот параметр не указывается, то по умолчанию тень не будет размытой.

Четвёртое значение – растяжение тени. По умолчанию тень того же размера, что и элемент.

Пятое значение – цвет тени. Цвет тени можно задать как в  RGB-формате так и в RGBA-формате. По умолчанию цвет чёрный.

img {width: 300px;height: 150px;border: 1px solid #000;border-radius: 10px;box-shadow:5px 5px 10px #2B1015;
}

Обтекание изображения текстом.

Для наглядности в index.html добавьте текст.

<!DOCTYPE html><html>     <head>          <meta charset=»utf-8″>          <link rel= «stylesheet» type= «text/css» href= «style.css» />          <title>Изображения</title>     </head>     <body>          <img src=»images/img1.jpg»>          <p>Это текст, который обтекает изображение справа.</p>          <p>Для наглядности напишем несколько абзацев</p>          <p>Абзац первый</p>          <p>Абзац второй</p>          <p>Абзац третий</p>          <p>А этот абзац обтекает изображение уже снизу.</p>     </body> </html>

Если мы хотим, чтобы изображение располагалось слева, а текст обтекал его справа, используем свойство float , значением которого будет left.

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

img {width: 300px;height: 150px;border: 1px solid #000;border-radius: 10px;box-shadow:5px 5px 10px #2B1015;float: left;margin-right: 20px;
}

Вертикальное и горизонтальное центрирование в CSS уровня 3

Мы можем расширить оба метода, чтобы центрировать по горизонтали и по вертикали одновременно.

Побочный эффект абсолютного позиционирования абзаца состоит в том, что абзац становится ровно таким широким, каким он должен быть (если только мы явно не укажем ширину). В примере ниже мы именно этого и хотим: мы размещаем по центру абзац из одного слова (“Центр!“), так что ширина абзаца должна быть равна ширине этого слова.

Центр!

Жёлтый фон наглядно демонстрирует, что абзац действительно той же ширины, что и его содержимое. Мы подразумеваем, что разметка осталась прежней:

<div class=container4>
  <p>Центр!
</div>

В плане вертикального центрирования эта таблица стилей схожа с таблицей из предыдущего примера. Но теперь мы ещё перемещаем элемент на полпути через контейнер с помощью правила ‘left: 50%’ и одновременно сдвигаем его влево на половину своей собственной ширины в преобразовании ‘translate’:

div.container4 {
    height: 10em;
    position: relative }
div.container4 p {
    margin: 0;
    background: yellow;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-right: -50%;
    transform: translate(-50%, -50%) }

Следующий пример объясняет, зачем требуется правило ‘margin-right: -50%’.

Когда форматер CSS поддерживает ‘flex’, всё становится ещё легче:

Центр!

с этой таблицей стилей:

div.container6 {
  height: 10em;
  display: flex;
  align-items: center;
  justify-content: center }
div.container6 p {
  margin: 0 }

Центрирование блока или изображения

Иногда центрировать нужно не текст, а блок в целом. Или, по-другому говоря: мы хотим, чтобы правое и левое поля были одинаковыми. Для этого нужно установить поля на ‘auto’. Это обычно используется для блоков с фиксированной шириной, потому что если блок сам по себе гибкий, он просто займёт всю доступную ширину. Вот пример:

P.blocktext {
    margin-left: auto;
    margin-right: auto;
    width: 6em
}
...
<P class="blocktext">Этот довольно ...

Этот довольно узкий блок текста центрирован. Заметьте, что строки внутри блока не центрированы (они выровнены влево), в отличие от предыдущего примера.

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

IMG.displayed {
    display: block;
    margin-left: auto;
    margin-right: auto }
...
<IMG class="displayed" src="..." alt="...">

How to Set Background Position

After adding a background image and stopping it from repeating, we are able to further control how it looks within the background of the tag by improving its position.

We’ll use the property to do this.

The selector takes in two values. The first one is for the horizontal position, or x-direction (how far across the tag). The second one is for the vertical position, or y-direction (how far down the tag).

The values can be units, like a pair of pixels:

This will move the image 20px across and 30px down the containing tag.

Instead of pixels we can use a set of keywords like right, left, top, down, or center to place the image at the right, left, top, down, or center of the tag.

This places the image at the right hand side of the center of the tag.

If we wanted to center it both horizontally and vertically, we would do the following:

To position an image with finer detail, it is worth mentioning that we can use percentages.

This positions the image 20% across the tag and 40% down the tag.

So far we have seen values used in combination, but we can also just specify one value like or or , which applies it to both directions.

Примеры

Пример

Устанавливает два фоновых изображения для элемента <body>. Пусть первое изображение появляется только один раз (без повтора), и пусть повторяется второе изображение:

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

Пример

Устанавливает линейный градиент (два цвета) в качестве фонового изображения для элемента <div>:

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

Пример

Устанавливает линейный градиент (три цвета) в качестве фонового изображения для элемента <div>:

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

Пример

Функция repeating-linear-gradient() используется для повторения линейных градиентов:

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

Пример

Устанавливает радиальный градиент (два цвета) в качестве фонового изображения для элемента <div>:

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

Пример

Устанавливает радиальный градиент (три цвета) в качестве фонового изображения для элемента <div>:

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

Пример

Функция repeating-radial-gradient() используется для повторения радиальных градиентов:

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

Multiple backgrounds #

As mentioned at the beginning of the module, the background layer allows multiple sublayers to be defined. For brevity, I’ll refer to these sublayers as backgrounds.

Multiple backgrounds are defined top to bottom; The first background is the closest to the user, while the last background is the furthest from the user.

The only background defined or the last layer is designated the final background layer by the browser. Only this layer is allowed to assign a .

Multiple layers can be individually configured using most background-related CSS properties that are comma separated, as demonstrated in the code snippet and live demo below.

Repeating background images #

By default, background images repeat horizontally and vertically to fill the entire space of the background layer.

Change this by using the property with one of the following values:

  • : The image repeats within the space available, cropping as necessary.
  • : The image repeats horizontally and vertically to fit as many instances into the space available, without cropping, compressing, or stretching it.
  • : The image repeats horizontally and vertically to fit as many instances within the space available without cropping—spacing out instances of the image as needed. Repeating images touch the edges of the space a background layer occupies, with white space evenly distributed between them.

The property allows you to set the behavior for the x and y axis independently. The first parameter sets the horizontal repeat behavior, and the second parameter sets the vertical repeat behavior.

If you use a single value, it will be applied to both the horizontal and vertical repeats.

The shorthand also has convenient one-word options to make your intent clearer.

The value repeats an image only horizontally; this is equivalent to .

The following demo demonstrates these capabilities of the property:

Гость форума
От: admin

Эта тема закрыта для публикации ответов.