Frage

I have an image which has reduced opacity and some text, which is in a separate div, which is lying over the image (negative margin-top). While the image should be transparent, the text should not. I now found out that, depending on the value of the opacity the text is shown in black or also transparent.

When the image has

opacity: 1

the text ist black, when the value lower - the text has an reduced opacity as well. My markup looks like this:

<li>
    <img src="image.jpg">
    <div class="text">Description</div>
</li>

.text{ margin-top: -3em; }
img{ opacity: 0.5; }

http://jsfiddle.net/BFhau/1/

How can I display the text always in black?

War es hilfreich?

Lösung

Add

position: relative;

to place text at the top.

Demo


The problem was setting opacity different than 1 creates an stacking context.

Then, according to the order defined in the spec, images overlap texts, because:

  • (4) .text are in-flow, non-positioned, block-level elements
  • (6) Images are inline elements that generate a stacking context

Since 4 < 6, images overlap text.

To avoid that, you can make .text positioned elements adding position: relative. Now they will fall into this category:

  • (8) Positioned descendants with 'z-index: auto' or 'z-index: 0'

Now, since 6 < 8, texts overlap images.

Alternatively, you could also add a positive z-index (e.g. z-index:1) in order to make .text fall into the next category:

  • (9) Stacking contexts formed by positioned descendants with z-indices greater than or equal to 1

You can read more about stacking contexts and z-axis positioning in What No One Told You About Z-Index, a great article much more appealing than the raw spec.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top