In HTML / CSS, you can repeat the image in the foreground, how can you in the background?

This is my CSS.

.test {
  background-image:url('images/smiley.gif');
  background-repeat:repeat;
}

This is my HTML:

<div class="test" id="xyz">some code which should come background to image</div>

The code I wrote sets the background image.

But I want to put an image on top of the text instead, so that it covers the text. (I also want it to repeat automatically to fill in an element, which can be any size.)

How can i do this?

+5
source share
3 answers

An interesting challenge. I think this should do it if you want to add an extra HTML element. (Alternatively, use .test:beforeinstead .test .foregroundImage, as in Georges answer ).

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

See http://jsfiddle.net/RUJYf/ for a working example.

+2

. :before div content ( , , , , div ), . , div background-image, height width, z-index of 1, 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 answer, .

, :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>
+4

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>
+1
source

All Articles