Monday, March 7, 2011

Change an image to text via CSS for printing?

Lets say I have a header banner on a webpage I'm about to print. Instead of wasting someone's ink printing the entire block of the image, is there a way via css to replace the image with text of H1 size?

From stackoverflow
  • You could put an h1 element and an image in the same place in the source, and have the image CSS display:none for print media, and have the h1 set to display:none for screen media.

  • Bryan, typically on things like logos I use image replacement for the graphic anyway so the logo itself is really in an H1 tag. Then in my print style sheet. I do something like this...

    h1#logo a, h1#home-logo{
        text-indent: 0 !important;
        background-image: none !important;
        font-size: 1.2em !important;
        display: block !important;
        height: 1em !important;
        width: 100% !important;
        text-decoration: none !important;
        color: black !important;
    }
    

    Which removes the image replacement and shows the text. Make sure of course that you call this stylesheet separately using media="print".

  • I usually just add the following to my style sheet:

    .nodisplay
    {
        display: none;
    }
    
    @media print {
        * {
         background-color: white !important;
         background-image: none !important;
        }
        .noprint
        {
         display: none;
        }
    }
    

    And then assign the noprint class to elements which shouldn't be printed:

    <div class="noprint">
    
    </div>
    

    And for your example, something like the following should work:

    <img src="logo.png" class="noprint" ...>
    <h1 class="nodisplay">Text Logo</h1>
    
  • Adding to Adam's solution: If your text is fixed ("head banner was there" not "ad for such and such was there"), you can use :before or :after pseudo-elements to insert text instead of having the text pre-inserted in the HTML.

    I makes your HTML lighter if you are replacing many images with the same text.

    I have to say that I dislike this CSS feature, but it is there if you want to use it.

  • According to CSS spec this should display the alt attribute after the image. Then you would just have to hide the image but I haven't managed to get it to work right in FF3 or chrome.

    img:after{content: attr(alt);}
    

0 comments:

Post a Comment