0

I am trying to put text over an image like so:

.gallery-image {
  position: relative;
}
h2 {
  position: absolute;
  top: 200px;
  left: 0;
  width: 100%;
}
h2 span {
  color: white;
  font: bold 24px/45px Helvetica, Sans-Serif;
  letter-spacing: -1px;
  background: rgb(0, 0, 0);
  background: rgba(0, 0, 0, 0.7);
  padding: 10px;
}
<div class="gallery-image">
  <a href="#">
    <img src="image.jpg" width="280">
  </a>
  <h2><span>Text</span></h2>
</div>

but my text goes behind the image, what can I do to fix this?

DaniP
  • 37,813
  • 8
  • 65
  • 74
user979331
  • 11,039
  • 73
  • 223
  • 418

3 Answers3

6

Snippet is working for me, anyway:

  • Give the img a z-index: 2;

  • And the h2 a z-index: 3;

Christian
  • 152
  • 1
  • 11
  • 1
    I upvoted you because you suggested realistic `z-index` numbers. I hate seeing `9999999` and such, like there's realistically going to be another `9999998` elements stacked underneath that one -_-. – Mathew Thompson Jan 09 '15 at 16:25
  • 6
    You're right about one thing: the example is fine. but the `image` is not being positioned, so a `z-index` is not going to do anything, for example, in this fiddle `img` has `z-index` of 4, `h2` has one of 2, nothing changes: [EXAMPLE](http://jsfiddle.net/qba7htoc/) – jmore009 Jan 09 '15 at 16:26
  • As already mentioned "For a **positioned** box, the 'z-index' property specifies" Source: http://www.w3.org/TR/CSS21/visuren.html#z-index – secelite Jan 09 '15 at 16:29
0

.container {
  position: relative;
}
h2 {
  position: absolute;
  bottom: 10%;
  background: darkgray;
  padding: 1%;
  color: white;
}
<div class="container">
  <img src="http://placekitten.com/g/200/300" alt="" />
  <h2>THIS text</h2>
</div>

Something like this? I've just styled the h2 tag, removing the need for that span tag you were using, and reducing markup.

jbutler483
  • 24,074
  • 9
  • 92
  • 145
0

I feel this needs some explanation.

The example is working, but if it is in fact not working for OP, he/she can use z-index but simply calling z-index on the img tag is not going to work as demonstrated here. Changing the z-index of both the image and h2 will have no effect.

z-index only works on positioned elements. Since the parent element is position:relative you can use position: inherit on one of it's children (or simply set a position). In this case the img is wrapped in an anchor tag:

<a href="#">
   <img src="image.jpg" width="280">
 </a>

So applying a z-index to the img tag doesn't make sense anyways. Instead add it to the a:

a{
  position: inherit;
  z-index: 2;
}

Now if you change the z-index values of h2 and a you will see the element with the higher z-index number come forward:

EXAMPLE

jmore009
  • 12,863
  • 1
  • 19
  • 34