Robert Kusznier
Robert Kusznier

Reputation: 6911

CSS image replacement working with images off and transparent images

I'm looking for a CSS image replacement technique (image replacement described for example here) — you hide element text contents and show image instead — which will work with transparent images and show the replaced text when images are turned off (for example by Windows High Contrast Mode).

I know techniques, which work with images having non-transparent background, but they stop to work when the image has non-transparent background — the element's text is visible through the background.

One example of such a technique below - setting the desired background on absolutely positioned pseudo child, which renders over the element. The issue: the text which I want to hide is still visible.

Illustrated in this pen.

HTML

<div>Text which I want to replace by an image</div>

CSS

div {
  position: relative;
  width: 100px;
  height: 100px;
}

div::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url("http://icons.iconarchive.com/icons/mazenl77/I-like-buttons-3a/512/Perspective-Button-Go-icon.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
}

Other techniques hide the text even with transparent image, but then not show the text when images are disabled, which is something I need. I'm looking for a one that does both.

Upvotes: 1

Views: 190

Answers (1)

Scoots
Scoots

Reputation: 3102

Put a known opaque image over the top with a lower z-index than the replacement image, like a 1px x 1px white png.

div {
    position: relative;
    width: 100px;
    height: 100px;
}

div::before,
div::after {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

div::before {
    background-image: url('/images/white-pixel.png');
    z-index: 1;
}

div::after {
    background-image: url("http://icons.iconarchive.com/icons/mazenl77/I-like-buttons-3a/512/Perspective-Button-Go-icon.png");
    background-size: 100% 100%;
    background-repeat: no-repeat;
    z-index: 2;
}

You could take this a step further and actually base-64 encode the image and embed it directly into the stylesheet:

div::before {
    background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCA‌​QAAAC1HAwCAAAAC0lEQV‌​R42mP8/x8AAwMCAO+ip1‌​sAAAAASUVORK5CYII=');
    z-index: 1;
}

Upvotes: 1

Related Questions