This little trick should do the job. Using the :before
selector allows you to generate a pseudo-element that acts like a fake div
. By setting the content
attribute (in this case, just a space), you create this fake div
that can then be styled with properties like background-image
, height
, width
, and z-index
. This pseudo-element sits above the real div
(which has a z-index of zero) and gives the illusion of being behind it.
<!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>
You can see the combined approach with Paul D. Waite's insightful answer to achieve similar results without adding extra elements like spans.
In my initial thought process, I believed applying the :before
to .test :first-child:before
would make it a child of the xyz
div
, but as it turns out, it works just fine without that specificity.
If you want to test out how this looks, you can check out the live result on 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>