Несколько картинок фоном css

CSS Multiple Backgrounds

In this chapter you will learn how to add multiple background images to one element.

You will also learn about the following properties:

CSS Multiple Backgrounds

CSS allows you to add multiple background images for an element, through the background-image property.

The different background images are separated by commas, and the images are stacked on top of each other, where the first image is closest to the viewer.

The following example has two background images, the first image is a flower (aligned to the bottom and right) and the second image is a paper background (aligned to the top-left corner):

Example

#example1 <
background-image: url(img_flwr.gif), url(paper.gif);
background-position: right bottom, left top;
background-repeat: no-repeat, repeat;
>

Multiple background images can be specified using either the individual background properties (as above) or the background shorthand property.

The following example uses the background shorthand property (same result as example above):

Example

CSS Background Size

The CSS background-size 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.

Example

The two other possible values for background-size are contain and cover .

The contain 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.

Читайте также:  Three dots in python

The cover 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 contain and cover :

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 background-size 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 element (the 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

Hero Image

You could also use different background properties on a 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 background-origin 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 background-origin property:

Example

#example1 <
border: 10px solid black;
padding: 35px;
background: url(img_flwr.gif);
background-repeat: no-repeat;
background-origin: content-box;
>

Читайте также:  Build scripts in java

CSS background-clip Property

The CSS background-clip 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 background-clip 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)

Источник

Несколько фоновых картинок

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

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

Фон с тремя изображениями

Рис. 1. Фон с тремя изображениями

Отдельные изображения для фона позволяют менять их положение, а также анимировать, как показано в примере 2.

Пример 2. Анимированный фон

Подробнее про анимацию рассказывается далее.

Рассмотрим теперь как применять одну картинку для создания блока с рамкой (рис. 2). Ширина блока фиксированная, а высота тянется в зависимости от объёма содержимого блока.

Рисованная рамка

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

Читайте также:  Закрытие диалогового окна html

Подготовленное для фона изображение

Рис. 3. Подготовленное для фона изображение

Сам фон выводится свойством background , оно же задаёт и координаты нужного фрагмента. Параметры каждого фона перечисляются через запятую и в данном случае имеет значение их порядок. Нам требуется, чтобы верхняя и нижняя часть блока не перекрывались, поэтому ставим их первыми (пример 3). Цвет фона указывается последним.

Пример 3. Несколько фоновых картинок

Первый фон выводит верхнюю границу блока, второй фон — нижнюю, а третий вертикальные границы. Последним идёт цвет, который виден в прозрачной центральной части блока (рис. 4).

Вид рамки

См. также

Источник

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

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

Задать множественные фоны легко:

.myclass  background: background1, background 2, . , backgroundN; > 

Вы можете сделать это сокращённым свойством background и отдельными свойствами кроме background-color . Таким образом, следующие свойства могут быть определены в виде списка по одному на фон: background , background-attachment , background-clip , background-image , background-origin , background-position , background-repeat , background-size .

Пример

В этом примере три фона: логотип Firefox, линейный градиент и изображение пузырей:

HTML

div class="multi_bg_example">div> 

CSS

.multi_bg_example  width: 100%; height: 400px; background-image: url(firefox.png), url(bubbles.png), linear-gradient(to right, rgba(30, 75, 115, 1), rgba(255, 255, 255, 0)); background-repeat: no-repeat, no-repeat, no-repeat; background-position: bottom right, left, right; background: -moz-linear-gradient(to right, rgba(30, 75, 115, 1), rgba(255, 255, 255, 0)), -webkit-gradient(to right, rgba(30, 75, 115, 1), rgba(255, 255, 255, 0)), -ms-linear-gradient(to right, rgba(30, 75, 115, 1), rgba(255, 255, 255, 0)), linear-gradient(to right, rgba(30, 75, 115, 1), rgba(255, 255, 255, 0)); > 

Результат

(If image does not appear in CodePen, click the TIdy button in the CSS section)

Как вы можете видеть, логотип Firefox (первый в списке) расположен сверху, далее идёт градиент и в самом низу фон с пузырями. Каждое последующее под-свойство ( background-repeat и background-position ) применяется к соответствующим фонам. Например первое значение свойства background-repeat применяется к первому фону, и т.д.

Смотрите также

Found a content problem with this page?

This page was last modified on 26 мая 2023 г. by MDN contributors.

Your blueprint for a better internet.

Источник

Оцените статью