Css multiple background images. New way: multiple backgrounds with CSS3


When we talked about the background-image property at the beginning of this section, we didn't mention one feature: in CSS3, you can add multiple backgrounds to a single element by simply listing them separated by commas. This is especially necessary when an element with a background has a variable width or height, and the background must adapt to its size.

How to Set Multiple Backgrounds in CSS

We will show you an example that may well be useful in practice. Let's imagine that we need to place a block of text in a frame. The frame represents graphic file in PNG format:


In this problem, the height of the text is unknown to us - we do not know whether the text will fit completely within the frame or go beyond it. Because of this unknown quantity, we can't risk using the original frame design as a background. Nose using CSS we can make this frame extend as needed. To do this, you will have to divide the original drawing into graphic editor into three parts - top, bottom and middle - and save each file separately. Like this:

Top of the frame


Bottom of frame


Middle of the 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, and also write down other necessary styles:

Frame ( background-image: url(https://goo.gl/tKyzHt), /* top part frames */ url(https://goo.gl/SUKymM), /* bottom of the frame */ 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, /* top of the frame is not repeated */ no-repeat, /* bottom of the frame is not repeated */ repeat-y; /* the middle of the frame is repeated vertically */ background-size: contain; /* here for all backgrounds 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 one is a semicolon placed to indicate the end of the declaration. For convenience and better readability of the code, we recommend specifying each URL on a new line.

Background pictures are placed according to the principle of layers - one below the other. The background specified first will be on the top layer, the second background will be below the first, and the third will be below the first two. That's why we placed the picture with the middle of the frame at the very end - so that it does not overlap the top and bottom parts.

Next, the code sets the background-position and background-repeat properties for each background (the same order in which the background images are arranged). Yes, you guessed it right: if required, then you can specify the values ​​of other background properties, separated by commas. And if you need to apply one value to all backgrounds, you write it as usual (in our case, 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 contents of the block. What happens if we increase the amount of text in the block? Let's look:


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


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

Using shorthand notation

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

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

This option looks less cumbersome and is easier to understand.

You can add multiple background images to one element at once through a single background property. This allows you to get by with one element to create a complex background or one image, displaying it several times with various settings. All images with their parameters are listed separated by commas, with the image that is displayed on top of the other images indicated first, and the last, respectively, the lowest image. Example 1 shows how to create a background with three images.

Example 1. Three backgrounds

Background

If you need to separately set some style property for the background, like background-size as in the example above, then the parameters for each background are listed separated by commas. The result of this example is shown in Fig. 1.

Rice. 1. Background with three images

Individual background images allow you to change their position and also animate them, as shown in example 2.

Example 2. Animated background

Background

Let's now consider how to use one picture to create a block with a frame (Fig. 2). The width of the block is fixed, and the height varies depending on the volume of the block’s contents.

Rice. 2. Hand-drawn frame

The figure clearly shows the upper and lower parts, which need to be cut out in a graphics editor and positioned horizontally. The middle part is selected so that it is repeated vertically without seams. The picture has a pronounced repeating pattern, so there should be no difficulty in highlighting it. The result will be a prepared image (Fig. 3). The checkered field indicates transparency; it allows you to set a colored background along with images and easily change it through styles.

Rice. 3. Image prepared for the background

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

Example 3. Several background images

Background

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

Tezcatlipoca - “smoking mirror”, the main god of the Aztecs.

Human sacrifices were made to both gods.

The first background displays the top border of the block, the second background - the bottom, and the third - the vertical borders. The last one is the color that is visible in the transparent central part of the block (Fig. 4).

  • Tutorial

We have already touched on the capabilities of the CSS3 Backgrounds and Borders module, looking at working with shadows (box-shadow). Today we'll talk a little about another interesting feature - using 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 individual images weigh less in total 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 on top of 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 inside each other or placed in a row with appropriate positioning rules. Here's a simple example:

A block with the class "fishing" 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/mermaid.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 in this example three nested backgrounds and one block with fish located next to the “background” blocks. In theory, fish can be moved, for example, with using JavaScript or CSS3 Transitions/Animations.

By the way, this example for ".fishing" uses the new syntax for background positioning, 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 the fish yet.

Multiple backgrounds

A new option added to CSS3 comes to the rescue - the ability to define multiple background images for one element. 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 the individual images separated by commas. Additional rules, also a list, can set positioning, repetitions and other parameters for each image. Note the order in which the images are listed: layers are listed from left to right from topmost to bottommost.

The result is exactly the same:

One rule

If the fish do not need to be separated into 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 won’t show a picture of the result - believe me, it coincides with the two pictures above. But pay attention to the styles again, especially “background-repeat” - according to the specification, if part of the list at the end is missing, 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 defined 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 match 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 page design. 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 theme 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 the 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 distributes the individual parameters of the background images according to the appropriate rules. For example, for positioning there is “background-position”, and for shifts it is enough to change only this. However, there is a cost for using multiple images - this rule (and any similar one) requires you to list the position for all backgrounds defined for your block, and you cannot do this selectively.

To add animation to our fish background, you 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 using CSS3 Transitions/Animations, but this is a topic for a separate discussion.

Parallax and interactivity

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

Multiple background images are useful in such scenarios, since while we are talking only about the background (and not the content), their use allows us to avoid littering the html code and DOM. But everything comes at a price: I can't turn to individual elements compositions by name, id, class or some other parameter. I must explicitly remember the order of elements in the composition in the code, and for every change in any parameter of any element, in fact, I must glue together a 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 convenient javascript code, which will take care of the virtualization of relationships with individual layers, while leaving the html code of the page as clean as possible.

What about compatibility?

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

You can also use Modernizr to provide alternative solutions for browsers that don't support multiple backgrounds. As Chris Coyier wrote in his post 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 backward compatibility, you can simply declare background twice, however, this also has its disadvantages in the form of possible double loading of resources (this depends on the implementation css processing in a specific 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've already started thinking about Windows 8, keep in mind that you can use multiple backgrounds when developing metro style applications, since it uses the same engine as IE10.

P.s. On topic: I can’t help but remember the phenomenal article about the cicada principle.

Tags: Add tags

Today we will work on background images, which are set using the background property and its additional values. Let's consider a couple practical examples in the implementation of setting several backgrounds to the same element.

This can be useful in many cases and moments. Especially the use of pseudo elements in this case, since they are very flexible in parameters.

Lots of background images

In order not to create a block inside a block, the easiest way is to add one line of rules to the main element and thus get desired result. We can consider this a laconic option, especially since it eliminates the need to once again go into source. Everything will be done using CSS alone.

Blockimg( background: url("img/img2.png"),/*topmost background and then sequentially*/ url("img/img3.png"), url("img/img1.jpg"); background-position :370px center, 120px 150px, center center;/*position of images*/ background-repeat: no-repeat;/*repeat picture*/ background-color: #444;/*if background color is needed*/ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1); margin: 100px auto 15px; box-sizing: border-box; padding: 25px; width:700px; min-height: 300px; ) /*shortened version*/ .blockimg ( background: url("img/img2.png") no-repeat 370px center, url("img/img3.png") no-repeat 120px 150px, url("img/img1.jpg") no-repeat center center ; margin: 100px auto 15px; box-sizing: border-box; padding: 25px; width:700px; min-height: 300px; )

Explanation. Set the element background picture, indicating the path to its location. Separated by commas, we are given the opportunity to enter many more backgrounds, as can be seen in the code above. The order of their numbers determines which image will be on top of the others. That is, the first background is higher than all the others, and then the sequence follows the principle of a regular graphic editor.

Next is indicated Extra options through individual properties: position, repetition, size, if necessary, then color. Please also note that all parameters are written separated by commas, in the same order as the number of the picture.

And one last detail. The entire code can be shortened by using just one generic property, background . There is a second option in the code example that shows how this is done.

Background image via pseudo element

Also don't forget about alternative options as such are the before and after pseudo-elements. There is a positive advantage in their use - the image can be moved beyond the edge of the element, so that it does not disappear at the border, but is on top of it. This technique will come in handy if you need to create something like a 3D effect.

Blockimg( background: url("img/img1.jpg") no-repeat;/*element background*/ position:relative;/*positioning area*/ margin: 200px auto 15px; box-sizing: border-box; padding: 25px; width:700px; min-height: 300px; ) .blockimg::before( background: url("img/img1.png") no-repeat center center; bottom: 0; content: ""; height: 295px; left: 0; position: absolute;/*absolute positioning*/ right: 0; top: -150px; )

Explanation. In fact, everything is very simple. We set the background to the main element in the usual way. Next comes the key property position: relative; , which defines the area for moving another element that is in the main element and has the property position:absolute; .

Instead of another element, although formally it goes as a separate area, we use a pseudo-element. We give it an absolute position and position it in the place we need.







2024 gtavrl.ru.