Using CSS to replace text with an image is a well known practice. CSS-Tricks has a museum of some techniques (http://css-tricks.com/examples/ImageReplacement/).
But none of these allows for replacement with a fluid image (for example, a logo that stretches across 100% of a fluid page layout). Is it possible to use CSS to do a fluid image replacement?
Almost all image replacement techniques use a background-image. And I know that you can set background-size: 100%
. But it's not straightforward to get the height of the text element to scale with it's width because the browser doesn't consider the background image as part of the content.
I understand that any of the common image replacement techniques could be easily combined with media queries to incrementally change the size of the text element to specific height x width ratios that work. But that is incremental, not fluid.
I did find a blog post that discusses this (http://viljamis.com/blog/2011/fluid-image-replacement.php). But it turns out thay method actually requires putting an image in the html content. I'm looking for real text replacement.
Took some fiddling, but I figured out a way. The key is to use padding percentage to set the height, because padding-top
and padding-bottom
percentage is linked to container width (unlike height
, which is linked to container height).
html
<h1 class="logo">The Logo</h1>
css
h1.logo {
background-image: url('logo.png');
background-size: 100%;
width: 100%;
padding-top: 29.8%;
height: 0;
text-indent: -9999px;
}
Where padding-top
is calculated by dividing the image height by width.
Working example: http://jsfiddle.net/bXtRw/
I'll note that using overflow: hidden
instead of text-indent: -9999px
should also work. But I get unstable behavior in Firefox.
Also, using font-size: 0
instead of height: 0
produces unstable behavior in Firefox.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With