Use DIV as background for another element

If I have a div containing images and text, can this div content be used as a background for, say, section ?

For example, something like this:

HTML:

 <section id="sec1"> <div id="bg-div"> <em>This is a background</em> <img src="image1"> <img src="image2"> </div> </section> 

And CSS:

 #sec1 { background: src(#bg-div); } 

That way, I could have this content div acting as the background for my section .

+5
source share
2 answers

Here I made an example with two divs:

  • .content that contains everything you need in the interface
  • .background - text, images and everything else in the background

To wrap one div on another (make an overlay), you have to put them in the same element, in this example it is a #wrapper div. Positive position: relative and width / height for the wrapper; position: relative should also be set for your content div and position: absolute; top: 0; left: 0; for your background.

The final step is to install z-index. An item with a higher z-index value is displayed above items with a lower z-index value. In other words, you should set the z-index for the background div less than for the contents of the div.

Final HTML:

 <div id="wrapper"> <div class="content"> <p>This text is in frontend</p> </div> <div class="background"> <p>Background text</p> <img src="http://nuclearpixel.com/content/icons/2010-02-09_stellar_icons_from_space_from_2005/earth_128.png" alt="background" /> <img src="http://upload.wikimedia.org/wikipedia/en/0/0c/IrfanView_Logo.png" alt="background 2" /> </div> </div> 

Final CSS:

 #wrapper{ position: relative; width: 200px; height: 200px; } .content{ color: #FFFFFF; font-size: 26px; font-weight: bold; text-shadow: -1px -1px 1px #000, 1px 1px 1px #000; position: relative; z-index: 100; } .background{ color: #999999; position: absolute; top: 0; left: 0; z-index: -100; } 

View a live example:

http://jsfiddle.net/1fevoyze/

+15
source

Use the CSS element() function. See https://developer.mozilla.org/en-US/docs/Web/CSS/element . Currently only available in FF under the -moz-element prefix. Example:

 <div style="width:400px; height:100px; background:-moz-element(#backgroundElt);"> 

An alternative would be to play with the SVG tag foreignObject , cloning the HTML for the element you want to use as a background.

Spec is located at http://dev.w3.org/csswg/css-images/#element-notation .

+1
source

Source: https://habr.com/ru/post/1203123/


All Articles