这是我的CSS
.test {
background-image:url('images/smiley.gif');
background-repeat:repeat;
}
这是我的 HTML:
<div class="test" id="xyz">some code which should come background to image</div>
我编写的代码设置了背景图像。
但是我想把一个图像放在文本的顶部,而不是在它后面,这样它就可以覆盖文本。(我还希望它自动重复以填充元素,可以是任何大小。
我该怎么做?
这应该可以解决问题。 :before
选择器使用给定的content
创建一个假div
(这里是一个空格,因为没有 content 属性,我认为使用空字符串内容,不会创建假div
),并且可以设置样式。因此,假div
被创建,并用background-image
、给定的height
和width
以及1
的z-index
进行样式设置,而真正的div
的 z 指数为零,如下所示。
<!DOCTYPE html>
<html>
<head>
<title>Test page</title>
<style>
.test:before {
content: " ";
position: absolute;
width: 100px; height: 100px;
background-image:url('http://upload.wikimedia.org/wikipedia/commons/a/a4/Smiley_transparent.png');
background-repeat:repeat;
z-index: 1;
}
.test {
z-index: 0;
}
</style>
</head>
<body>
<div class="test" id="xyz">some code which should come background to image</div>
</body>
</html>
将此与 Paul D. Waite 的答案相结合,可以避免在代码中出现显式跨度。
我认为:before
必须应用于.test :first-child:before
,所以它将是xyz
div
的孩子,而不是兄弟姐妹,但似乎没有必要(尽管它逃脱了我为什么)。
您可以在 jsfiddle 上实时测试结果。
<!DOCTYPE html>
<html>
<head>
<title>Test page</title>
<style>
.test {
position: relative;
}
.test:before {
content: " ";
position: absolute;
top: 0;
bottom: 0;
height: auto;
left: 0;
right: 0;
width: auto;
background-image:url('http://upload.wikimedia.org/wikipedia/commons/a/a4/Smiley_transparent.png');
background-repeat:repeat;
}
</style>
</head>
<body>
Some text before.
<div class="test" id="xyz">some code which should come background to image</div>
Some text after.
</body>
</html>
有趣的任务。我认为这应该可以做到,如果你愿意放入一个额外的 HTML 元素。(或者,使用.test:before
而不是.test .foregroundImage
,就像乔治的回答一样)。
.HTML
<div class="test" id="xyz"><span class="foregroundImage"></span>some code which should come background to image</div>
.CSS
.test {
position: relative;
}
.test .foregroundImage {
position: absolute;
top: 0;
bottom: 0;
height: auto;
left: 0;
right: 0;
width: auto;
background-image:url('images/smiley.gif');
background-repeat:repeat;
}
有关工作示例,请参阅 http://jsfiddle.net/RUJYf/。
CSS
<style type="text/css">
.test { position: relative; }
.test img, .test p { position: absolute; top: 0; }
.test img { z-index: 10; }
.test p { margin: 0; padding: 0; }
</style>
.HTML
<div class="test">
<img src="images/smiley.gif" />
<p>some code which should come background to image</p>
</div>