使用 DIV 作为另一个元素的背景 [英] Use a DIV as a background for another element

查看:42
本文介绍了使用 DIV 作为另一个元素的背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个包含图像和文本的 div,是否可以将此 div 的内容用作例如 的背景部分 ?

If I have a div that contains images and text, is it possible to use this div's content as a background for, let's say, a section ?

例如,类似的东西:

HTML:

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

还有 CSS:

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

这样,我可以让这个 div 内容充当我的 section 的背景.

This way, I could have this div content acting like a background for my section.

推荐答案

这里我做了一个2个div的例子:

Here I made an example with 2 divs:

  • .content 包含你在前端需要的一切
  • .background - 在背景中包含文本、图像和其他所有内容

要将一个 div 覆盖在另一个上(制作覆盖),您必须将它们放入同一个元素中,在此示例中为 #wrapper div.放置位置:包装器的相对和宽度/高度;position: relative 也应该为您的内容 div 和 position: absolute 设置;顶部:0;左:0;为你的背景.

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

最后一步是设置 z-index.z-index 中包含较大值的元素呈现在 z-index 值较小的元素上方.换句话说,您应该将背景 div 的 z-index 设置为比内容 div 小.

The final step is to setup z-index. Element containing a bigger value in z-index is rendered above elements with smaller z-index value. In other words you should set z-index for background div smaller then for content div.

最终的 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>

最终 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;
}

查看实时示例:

http://jsfiddle.net/1fevoyze/

这篇关于使用 DIV 作为另一个元素的背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆