• Print.css specific for WordPress

    I wanted to print a page exactly the same way it is displayed on screen. It has been a process of trail and error to get it working. I collected tips and tricks from various websites which I will summarize here. The basics for adding a print stylesheet to wordpress are covered in this blog post.

    1. Empty pages

    The first thing I ran into was the print preview showed a range of empty pages. Empty pages are caused by page-breaks inserted by tags like e.g. <header>, <section>, <h1>, etc. To avoid page-breaks you can use the following css.

    div,
    main,
    section,
    article,
    aside,
    header,
    figure,
    ul,
    p,
    tr,
    img,
    svg,
    hr,
    h1,
    h2,  
    h3,
    h4,
    pre, 
    blockquote {	
    	page-break-before: avoid !important;
    	page-break-inside: avoid !important;
    	page-break-after: avoid !important;
    }

    Although this code avoids page-breaks the following solution had the side-effect that it removed the unwanted page-breaks also.

    2. Hide page-sections

    There are two ways to hide page-sections: display:none and visibility:hidden.

    display:none means that the tag in question will not appear on the page at all (although you can still interact with it through the dom). There will be no space allocated for it between the other tags. For print.css this is useful to permanently remove tags and their children.

    visibility:hidden means that unlike display:none, the tag is not visible, but space is allocated for it on the page. The tag is rendered, it just isn’t seen on the page. For print.css this can be used to hide parent-tags but make child-tags visible again. Adding zero padding and margin will visually hide it.

    WordPress themes are constructed with HTML5 web page layout elements. When you print the page you often don’t want to print all of these sections.

    In my case I only needed the <article> and <section>. In my print.css I turned the world around by hiding all elements by default.

    /* Hide all elements by default */  
    * {   
    	visibility: hidden !important;        
    }

    And then I made the tags visible I wanted to see.

    /* Show elements we want to see */
    body,
    section,
    article,
    figure,
    img,
    strong,
    hr,
    article div,
    article p,
    article h2,
    article h3,
    article h4 {
    	visibility: visible !important;
    }

    To hide the tags I permanently want to hide I used the following css

    script, /* no scripts need to print */ 
    style, /* remove unwanted inline styles */
    header,
    footer,
    .mobile-header, /* only visible on mobile devices but could cause page-breaks */
    aside { 
        display: none !important; 
    }
  • Geef een reactie