23.07.2020

How to make css double background. Several background pictures. The Future: CSS3 Pseudo-Elements


A task

Add two background images for the block with using CSS 3.

Solution

Modern browsers allow you to add an arbitrary number of background images to an element, listing the parameters of each background separated by commas. It is enough to use the universal background property and specify one background for it first and the second one separated by a comma.

For example, consider creating vertical decorative lines to the left and right of the block. To do this, we first prepare images that should be repeated vertically without joints. On fig. 1 shows a background image that will be displayed on the left edge, and in fig. 2 picture to display on the right side.

Rice. 1. Background image for the border on the left

Rice. 2. Background image for the border on the right

The tag is usually used as a block element to which the background is added.

due to its convenience and versatility, in order to distinguish it from other elements, the block class is added to it (example 1).

Example 1: Two background images

HTML5 CSS3 IE Cr Op Sa Fx

Two background images

During 11 months of the shift, radio operators conducted 8642 communication sessions with a total volume of 300625 groups. This is only weather and airtelegrams. Received from Cape Chelyuskin radio station 7450 groups.

The result of this example is shown in Fig. 3.

). Today we will talk a little about another interesting opportunity— use of several images in the background.

Background composition

There are many reasons why you might want to compose multiple images in the background at all, the most important of which are:

  • saving traffic on the size of images, if individual images weigh less than the flattened image, and
  • the need for independent behavior of individual layers, for example, when implementing parallax effects.
There may be other reasonable reasons :)

Classic approach

So, we need to place several background images one above the other. How is this problem usually solved? It's very simple: for each background image, a block is created, to which the corresponding background image is assigned. Blocks are either nested or placed in a row with appropriate positioning rules. Here is a simple example:

The "fishing" class block inside "mermaid" is for demonstration purposes only.

Now some styles:
.sample1 .sea, .sample1 .mermaid, .sample1 .fishing ( height:300px; width:480px; position: relative; ) .sample1 .sea ( background: url(media/sea.png) repeat-x top left; ) .sample1 .mermaid ( background: url(media/fish.svg) repeat-x bottom left; ) .sample1 .fish ( background: url(media/fish.svg) no-repeat; height:70px; width:100px; left : 30px; top: 90px; position: absolute; ) .sample1 .fishing ( background: url(media/fishing.svg) no-repeat top right 10px; )

Result:

AT this example three nested backgrounds and one block with fish, located next to the "background" blocks. In theory, the fish can be moved, for example, using JavaScript or CSS3 Transitions/Animations.

Incidentally, this example uses the new syntax for background positioning for ".fishing", also defined in CSS3:
background: url(media/fishing.svg) no-repeat top right 10px;
It is currently supported in IE9+ and Opera 11+, but is not supported in Firefox 10 and Chrome 16. So users of the last two browsers will not be able to catch a fish yet.

Multiple backgrounds

A new option added to CSS3 comes to the rescue - the ability to define multiple background images for a single element at once. It looks like this:

And the corresponding styles:
.sample2 .sea ( height:300px; width:480px; position: relative; background-image: url("media/fishing.svg"), url("media/mermaid.svg"), url("media/sea. png"); background-position: top right 10px, bottom left, top left; background-repeat: no-repeat, repeat-x, repeat-x ; ) .sample2 .fish ( background: url("media/fish.svg ") no-repeat; height:70px; width:100px; left: 30px; top: 90px; position: absolute; )
To define multiple images, you must use the background-image rule, listing individual images separated by commas. Additional rules, also a list, can set positioning, repetitions and other parameters for each of the images. Pay attention to the order in which the images are listed: the layers are listed from left to right from the top to the bottom.

The result is exactly the same:

One rule

If the fish do not need to be allocated in a separate block for subsequent manipulations, the entire picture can be rewritten in one simple rule:

Styles:
.sample3 .sea ( height:300px; width:480px; position: relative; background-image: url("media/fishing.svg"), url("media/mermaid.svg"), url("media/fish. svg"), url("media/sea.png"); background-position: top right 10px, bottom left, 30px 90px, top left; background-repeat: no-repeat, repeat-x ; )

I will not give a picture with the result - believe me, it coincides with the two pictures above. But pay attention to styles again, especially to “background-repeat” - according to the specification, if part of the list at the end is skipped, then the browser must repeat the specified list the required number of times to match the number of images in the list.

In this case, it is equivalent to this description:
background-repeat: no-repeat, repeat-x, no-repeat, repeat-x;

Even shorter

If you remember CSS 2.1, it defines the ability to describe background images in a short form. How about multiple images? This is also possible:

Sample4 .sea ( height:300px; width:480px; position: relative; background: url("media/fishing.svg") top right 10px no-repeat, url("media/mermaid.svg") bottom left repeat-x , url("media/fish.svg") 30px 90px no-repeat, url("media/sea.png") repeat-x; )

But note that now you can’t just skip values ​​(unless they are the same as the default value). By the way, if you want to set the color of the background image, this must be done in the very last layer.

Dynamic Images

If the composition is static or dynamic no more than depending on the size of the container, then multiple backgrounds obviously simplify the design of the page. But what if you need to work with individual elements of the composition independently from javascript (move, scroll, etc.)?
By the way, here is an example from life - a topic with a dandelion in Yandex:


If you look into the code, you will see something like this:
...

Blocks with classes "b-fluff-bg", "b-fluff__cloud" and "b-fluff__item" contain background images that overlap each other. Moreover, the background with clouds constantly scrolls, and dandelions fly across the screen.

Can this be rewritten using multiple backgrounds? In principle, yes, but subject to 1) support for this feature in target browsers and… 2) read on ;)

How to add dynamics to multiple backgrounds? In such a situation, it turns out to be convenient that in the internal representation the browser scatters the individual parameters of the background image according to the appropriate rules. For example, for positioning there is “background-position”, and for shifts it is enough to change only it. However, there is a cost to using multiple images - this rule (and any similar one) needs to list the position for all the backgrounds set for your block, and cannot be done selectively.

To add animation to our fish background, we can use the following code:
$(document).ready(function() ( var sea = $(".sample5 .sea"); var fishesX = 30; var fishesY = 90; var fishX = 0; var fishY = 0; var mermaidX = 0; var t = 0; function animationLoop() ( fishesY = 90 + Math.floor(30 * Math.sin(t++ / 180.0)); if(--fishesX< 0) fishesX = 480; mermaidX += 0.5; if(mermaidX >480) mermaidX = 0; fishY = -10 + (10 * Math.cos(t * 0.091)); fishX = 10 + (5 * Math.sin(t * 0.07)); sea.style.backgroundPosition = "top " + fishY + "px right" + fishX + "px, " + mermaidX + "px bottom," + fishesX + "px " + fishesY + "px, top left"; window.requestAnimFrame(animationLoop); ) animationLoop(); ));
where
window.requestAnimFrame = (function() ( return window.requestAnimationFrame || window.msRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.webkitRequestAnimationFrame || (function(callback) ( window.setTimeout(callback, 1000 / 60 ); )); ))();

And, by the way, animations can also be done through CSS3 Transitions / Animations, but this is a topic for a separate discussion.

Parallax and interactive

Finally, with similar maneuvers, you can easily add parallax effects or interactive interaction with the background:

Multiple background images are handy in these scenarios because as long as we're only talking about the background (and not the content), using them avoids cluttering the html code and the DOM. But everything comes at a cost: I can't access individual composition elements by name, id, class, or any other parameter. I must explicitly remember the order of the elements in the composition in the code, and for each change in any parameter of any element, in fact, I must glue the line describing the values ​​of this parameter for all elements and update it for the entire composition.

Sea.style.backgroundPosition = "top " + fishY + "px right " + fishX + "px, " + mermaidX + "px bottom," + fishesX + "px " + fishesY + "px, top left";

I am sure that this can be wrapped in a convenient javascript code that will take care of the virtualization of relationships with individual layers, while leaving the html code of the page as clean as possible.

What's with compatibility?

All modern versions of popular browsers, including IE9+, support multiple images (you can check with caniuse, for example).

You can also use Modernizr to provide alternative solutions for browsers that don't support multiple backgrounds. As Chris Coyier wrote in a note about layer order when using multiple backgrounds, do something like this:

Multiplebgs body ( /* Awesome multiple BG declarations that transcend reality and imsourcess chicks */ ) .no-multiplebgs body ( /* laaaaaame fallback */ )
If you are confused about using JS to provide backwards compatibility, you can simply declare background twice, however, this also has its drawbacks in the form of a possible double loading of resources (this depends on the implementation of css processing in a particular browser):

/* multiple bg fallback */ background: #000 url(...) ...; /* Awesome multiple BG declarations that transcend reality and imsourcess chicks */ background url(...), url(...), url(...), #000 url(...);

If you have already started thinking about Windows 8, keep in mind that you can use multiple backgrounds when developing metro style applications, since the same engine is used internally as in IE10.

P.s. On the subject: I can’t help but recall a phenomenal article about

When talking about the background-image property at the beginning of the section, we didn't mention one feature: in CSS3, you can add multiple backgrounds to the same element by simply listing them separated by commas. This is especially useful when the background element has a non-constant width or height, and the background needs to adjust to its size.

How to set multiple backgrounds in CSS

We will show you an example that may well come in handy in practice. Imagine that we need to place a block with text in a frame. The frame is graphic file in PNG format:


In this problem, we don't know the height of the text - we don't know if the text will fit completely into the frame or go beyond it. Because of this unknown value, we can't risk using the original frame drawing as the background. But with the help of CSS, we can make this border grow as needed. To do this, you will have to split the original drawing into graphics editor into three parts - top, bottom and middle - and save each file separately. Like this:

Top frame


Bottom frame


middle frame


We will make the background with the image of the middle of the frame repeating along the axis Y, while the top and bottom of the frame will not be duplicated. Let's add all three backgrounds to the element, as well as write other necessary styles:

Frame ( background-image: url(https://goo.gl/tKyzHt), /* frame top */ url(https://goo.gl/SUKymM), /* frame bottom */ url(https: //goo.gl/Km7HVV); /* middle of the frame */ background-position: center top, /* position of the top of the frame */ center bottom, /* position of the bottom of the frame */ center top; /* position of the middle of the frame */ background -repeat: no-repeat, /* the top of the frame is not repeated */ no-repeat, /* the bottom of the frame is not repeated */ repeat-y; /* the middle of the frame is repeated vertically */ background-size: contain; /* here for all backgrounds have the same value */ height: auto; /* block height depends on the amount of content */ width: 400px; /* block width is fixed */ padding: 30px; /* block padding */ )

Each background must be separated by a comma, and only after the last is a semicolon, indicating the end of the declaration. For convenience and better readability of the code, we recommend that you specify each URL on a new line.

Background images are placed on the principle of layers - one under the other. The background specified first will be in the top layer, the second background - under the first, the third - under the first two. That is why we put the picture with the middle of the frame at the very end - so that it does not overlap with the top and bottom parts.

The code then sets the background-position and background-repeat properties for each background (keeping the same order as the background images). Yes, you guessed it right: if required, you can also specify values ​​of other background properties separated by commas. And if you need to apply one value for all backgrounds, you write it down as usual (in our case, this is the background-size: contain property).

Well, let's take a look at the result:


As you can see, the frame is positioned correctly, and now it beautifully frames the content of the block. What will happen if we increase the amount of text in the block? We look:


The middle part of our frame was duplicated vertically the required number of times, as if stretching in length and adjusting to the text. This is the effect that could not be realized if we used a single frame image. Let's add even more text for clarity:


Of course, several backgrounds can be used to solve other problems. We have shown just one example out of many. Try to come up with your own situation and practice using a group of backgrounds.

Abbreviated notation

The background property also accepts multiple values. In the case of using multiple backgrounds, abbreviated notation can be much more convenient, because it is more difficult to get confused in it. Let's redo our frame code:

Background: url(https://goo.gl/tKyzHt) center top / contain no-repeat, /* frame top */ url(https://goo.gl/SUKymM) center bottom / contain no-repeat, /* frame bottom */ url(https://goo.gl/Km7HVV) center top / contain repeat-y; /* middle of frame */

This option looks less cumbersome and easier to perceive.

In CSS 2, adding two backgrounds to the same element at the same time is unrealistic, so you have to nest one element inside another and set your own background image for each. For complex layouts of such attachments, sometimes you can count about a dozen. It is clear that such a heap does not lead to anything good, but what to do? It turns out there is something! In CSS 3, you can add multiple background images to any element at the same time. So we take the block drawing (Fig. 1), cut it into pieces and start testing in browsers.

Rice. 1. Block for the site

For simplicity, I will take the width of the block as a fixed size, and the height will stretch depending on the content. The figure clearly shows the upper and lower parts, I cut it out in the editor and fold it in layers in a separate file. The middle part must be chosen so that it repeats without seams vertically. The drawing has a well-defined repeating ornament, so there should be no difficulty in highlighting. I copy and paste to the previous fragments. As a result, we get such a picture (Fig. 2).

Rice. 2. Prepared images

In principle, you can save each fragment as a separate file, but CSS sprites (the so-called technology for gluing several images into one) have a number of advantages. Firstly, the number of requests to the server is reduced due to the reduction in the number of files and, secondly, the images in total are loaded and displayed faster.

The background itself is displayed by the background property, which also sets the coordinates of the desired fragment. The parameters of each background are listed separated by commas, and in this case their order matters. I want the top and bottom of the block to not overlap, so I put them first (example 1).

Example 1. Multiple background images

HTML5 CSS2.1 CSS3 IE 8 IE 9 Cr Op Sa Fx

Three backgrounds

Huitzilopochtli - "the hummingbird sorcerer", the god of war and the sun.

Tezcatlipoca - "smoking mirror", the main god of the Aztecs.

Both gods were offered human sacrifices.

The first background displays the top border of the block, the second background - the bottom, and the third - the vertical borders.

We check in browsers. Internet Explorer 8 did not display any images at all, other browsers (IE 9, Opera 10.60, Firefox 3.6, Chrome 5, Safari 5) displayed the frame correctly (Fig. 3).

Rice. 3. Frame view in Safari browser

With the use of multiple backgrounds, the situation for developers is greatly facilitated, especially when laying out blocks. There is only one little thing left. It is necessary that the IE 6-8 browser cease to exist.

). Today we will talk a little about another interesting feature - the use of multiple images in the background.

Background composition

There are many reasons why you might want to compose multiple images in the background at all, the most important of which are:

  • saving traffic on the size of images, if the individual images in total weigh less than an image with flattened layers, and
  • the need for independent behavior of individual layers, for example, when implementing parallax effects.
There may be other reasonable reasons :)

Classic approach

So, we need to place several background images one above the other. How is this problem usually solved? It's very simple: for each background image, a block is created, to which the corresponding background image is assigned. Blocks are either nested or placed in a row with appropriate positioning rules. Here is a simple example:

The "fishing" class block inside "mermaid" is for demonstration purposes only.

Now some styles:
.sample1 .sea, .sample1 .mermaid, .sample1 .fishing ( height:300px; width:480px; position: relative; ) .sample1 .sea ( background: url(media/sea.png) repeat-x top left; ) .sample1 .mermaid ( background: url(media/fish.svg) repeat-x bottom left; ) .sample1 .fish ( background: url(media/fish.svg) no-repeat; height:70px; width:100px; left : 30px; top: 90px; position: absolute; ) .sample1 .fishing ( background: url(media/fishing.svg) no-repeat top right 10px; )

Result:

In this example, there are three nested backgrounds and one fish box next to the "background" boxes. In theory, the fish can be moved, for example, using JavaScript or CSS3 Transitions/Animations.

Incidentally, this example uses the new syntax for background positioning for ".fishing", also defined in CSS3:
background: url(media/fishing.svg) no-repeat top right 10px;
It is currently supported in IE9+ and Opera 11+, but is not supported in Firefox 10 and Chrome 16. So users of the last two browsers will not be able to catch a fish yet.

Multiple backgrounds

A new option added to CSS3 comes to the rescue - the ability to define multiple background images for a single element at once. It looks like this:

And the corresponding styles:
.sample2 .sea ( height:300px; width:480px; position: relative; background-image: url("media/fishing.svg"), url("media/mermaid.svg"), url("media/sea. png"); background-position: top right 10px, bottom left, top left; background-repeat: no-repeat, repeat-x, repeat-x ; ) .sample2 .fish ( background: url("media/fish.svg ") no-repeat; height:70px; width:100px; left: 30px; top: 90px; position: absolute; )
To define multiple images, you must use the background-image rule, listing individual images separated by commas. Additional rules, also a list, can set positioning, repetitions and other parameters for each of the images. Pay attention to the order in which the images are listed: the layers are listed from left to right from the top to the bottom.

The result is exactly the same:

One rule

If the fish do not need to be allocated in a separate block for subsequent manipulations, the entire picture can be rewritten with one simple rule:

Styles:
.sample3 .sea ( height:300px; width:480px; position: relative; background-image: url("media/fishing.svg"), url("media/mermaid.svg"), url("media/fish. svg"), url("media/sea.png"); background-position: top right 10px, bottom left, 30px 90px, top left; background-repeat: no-repeat, repeat-x ; )

I will not give a picture with the result - believe me, it coincides with the two pictures above. But pay attention to styles again, especially to “background-repeat” - according to the specification, if part of the list at the end is skipped, then the browser must repeat the specified list the required number of times to match the number of images in the list.

In this case, it is equivalent to this description:
background-repeat: no-repeat, repeat-x, no-repeat, repeat-x;

Even shorter

If you remember CSS 2.1, it defines the ability to describe background images in a short form. How about multiple images? This is also possible:

Sample4 .sea ( height:300px; width:480px; position: relative; background: url("media/fishing.svg") top right 10px no-repeat, url("media/mermaid.svg") bottom left repeat-x , url("media/fish.svg") 30px 90px no-repeat, url("media/sea.png") repeat-x; )

But note that now you can’t just skip values ​​(unless they are the same as the default value). By the way, if you want to set the color of the background image, this must be done in the very last layer.

Dynamic Images

If the composition is static or dynamic no more than depending on the size of the container, then multiple backgrounds obviously simplify the design of the page. But what if you need to work with individual elements of the composition independently from javascript (move, scroll, etc.)?
By the way, here is an example from life - a topic with a dandelion in Yandex:


If you look into the code, you will see something like this:
...

Blocks with classes "b-fluff-bg", "b-fluff__cloud" and "b-fluff__item" contain background images that overlap each other. Moreover, the background with clouds constantly scrolls, and dandelions fly across the screen.

Can this be rewritten using multiple backgrounds? In principle, yes, but subject to 1) support for this feature in target browsers and… 2) read on ;)

How to add dynamics to multiple backgrounds? In such a situation, it turns out to be convenient that in the internal representation the browser scatters the individual parameters of the background image according to the appropriate rules. For example, for positioning there is “background-position”, and for shifts it is enough to change only it. However, there is a cost to using multiple images - this rule (and any similar one) needs to list the position for all the backgrounds set for your block, and cannot be done selectively.

To add animation to our fish background, we can use the following code:
$(document).ready(function() ( var sea = $(".sample5 .sea"); var fishesX = 30; var fishesY = 90; var fishX = 0; var fishY = 0; var mermaidX = 0; var t = 0; function animationLoop() ( fishesY = 90 + Math.floor(30 * Math.sin(t++ / 180.0)); if(--fishesX< 0) fishesX = 480; mermaidX += 0.5; if(mermaidX >480) mermaidX = 0; fishY = -10 + (10 * Math.cos(t * 0.091)); fishX = 10 + (5 * Math.sin(t * 0.07)); sea.style.backgroundPosition = "top " + fishY + "px right" + fishX + "px, " + mermaidX + "px bottom," + fishesX + "px " + fishesY + "px, top left"; window.requestAnimFrame(animationLoop); ) animationLoop(); ));
where
window.requestAnimFrame = (function() ( return window.requestAnimationFrame || window.msRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.webkitRequestAnimationFrame || (function(callback) ( window.setTimeout(callback, 1000 / 60 ); )); ))();

And, by the way, animations can also be done through CSS3 Transitions / Animations, but this is a topic for a separate discussion.

Parallax and interactive

Finally, with similar maneuvers, you can easily add parallax effects or interactive interaction with the background:

Multiple background images are handy in these scenarios because as long as we're only talking about the background (and not the content), using them avoids cluttering the html code and the DOM. But everything comes at a cost: I can't access individual composition elements by name, id, class, or any other parameter. I must explicitly remember the order of the elements in the composition in the code, and for each change in any parameter of any element, in fact, I must glue the line describing the values ​​of this parameter for all elements and update it for the entire composition.

Sea.style.backgroundPosition = "top " + fishY + "px right " + fishX + "px, " + mermaidX + "px bottom," + fishesX + "px " + fishesY + "px, top left";

I am sure that this can be wrapped in a convenient javascript code that will take care of the virtualization of relationships with individual layers, while leaving the html code of the page as clean as possible.

What's with compatibility?

All modern versions of popular browsers, including IE9+, support multiple images (you can check with caniuse, for example).

You can also use Modernizr to provide alternative solutions for browsers that don't support multiple backgrounds. As Chris Coyier wrote in a note about layer order when using multiple backgrounds, do something like this:

Multiplebgs body ( /* Awesome multiple BG declarations that transcend reality and imsourcess chicks */ ) .no-multiplebgs body ( /* laaaaaame fallback */ )
If you are confused about using JS to provide backwards compatibility, you can simply declare background twice, however, this also has its drawbacks in the form of a possible double loading of resources (this depends on the implementation of css processing in a particular browser):

/* multiple bg fallback */ background: #000 url(...) ...; /* Awesome multiple BG declarations that transcend reality and imsourcess chicks */ background url(...), url(...), url(...), #000 url(...);

If you have already started thinking about Windows 8, keep in mind that you can use multiple backgrounds when developing metro style applications, since the same engine is used internally as in IE10.

P.s. On the subject: I can’t help but recall a phenomenal article about


2022
maccase.ru - Android. Brands. Iron. News