Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Rethinking CSS Image Replacement

DZone's Guide to

Rethinking CSS Image Replacement

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

When I say CSS image replacement, I mean taking a page element that isn't normally an image and turning it into an image. This is a very common trick and popular because of it's semantic meaningfulness and SEO benefits. A common place to use this is with a header tag.

The OLD Way


<h1 class="main-logo">
   CSS-Tricks
</h1>


h1.main-logo {
	width: 350px; height: 75px;
	background: url(images/header-image.jpg);
	text-indent: -9999px;
}


PROBLEM: If you turn CSS off, this will just degrade into text. Not a bad thing, but just because someone has their CSS turned off doesn't necessarily mean they want their images turned off too.

The NEW Way


<h1 class="main-logo">
   <a href="#">
       <img src="images/header-image.jpg" alt="CSS-Tricks" />
   </a>
</h1>


WHY THIS IS BETTER:

With CSS turned off you can still display an image. With CSS and images turned off, you will get the ALT text from the image. You can even use a different image inside than you used for your CSS image, if there is a good contextual reason to do so.

REMAINING PROBLEMS:

Neither of these techniques are perfect yet. While the latter solves one piece of the puzzle, there is still one missing piece. That is CSS ON, images OFF. In this scenario you will get blank space instead of either text or an image. Not great. The other issue is turning these elements into links. You can wrap the header tag in an anchor element, but wrapping a block element in an inline element is bad form. Make sure you change your anchor link to block level if you do this. The other option is a javascript onClick event.

NOTE:

I'm sure this has been thought of and used by people before, so "old" and "new" are kind of subjective here.

[EXAMPLE PAGE]

Thanks to Volkan Görgülü for the idea!

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}