Optimizing CSS for printing by eliminating unnecessary white space with media queries

Appreciate your assistance! I'm currently working on a solution to print a specific div using CSS Media queries. When the user clicks on print, I want to hide all other elements except for the body div they chose. However, I'm facing an issue where the hidden elements still appear in their original positions during printing due to the 'hidden' property. Display:none isn't feasible as it disrupts dynamically generated elements. Any advice on how to ensure that the selected elements are printed front and center on the first page would be greatly appreciated! Below is my CSS code for printing:

<style>
        /*HIDING ALL ELEMENTS EXCEPT THE PRINTED ONE*/
        @media print {
            /*Hide all HTML elements*/
            body * {
                visibility: hidden;
            }
            /*Make chosen elements and their children visible*/
            .section-to-print-head, .section-to-print-body, .section-to-print-head *, .section-to-print-body * {
                visibility: visible;
                display: block;

            }
            /*POSITION OF HEAD*/
            .section-to-print-head {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                page-break-after: avoid;
                display: block;
            }

            /*POSITION OF BODY*/
            .section-to-print-body {
                position: absolute;
                left: 5;
                top: 0;
                width: 100%;
                z-index: 100;
            }
            .section-to-print-body:last-child {
              page-break-after: avoid;
            }
        }
    </style>

Here's the HTML snippet with the button and onclick function:

<div class="row infoAreaToPrint">
            <div class="col-lg-5">
                <div class="card">
                    <div class="card-body">
                       <p class="h4 border-bottom mb-0">
                             Customer: <?php echo $custName ?></p>
                              <span>
                                 <button                                                          
                                  onclick="printThisTableDiv('.infoAreaToPrint')">Print Info</button>
                              </span>

This is the function I use to hide all elements except the one intended for printing:

function printThisTableDiv(tableID) {
        let existingTags = document.querySelectorAll('.section-to-print-body');
        let i;
        for (i = 0; i < existingTags.length; i++) {
            existingTags[i].classList.remove('section-to-print-body');
        }
        document.querySelector(tableID).classList.add("section-to-print-body");
        window.print();
    };

Answer №1

After some experimentation, I managed to solve the issue by simply updating the CSS query.

   @media print {

            html, body {
                height:100%;
                margin: 0 !important;
                padding: 0 !important;
                overflow: hidden;
            }

            /*Hiding all HTML elements*/
            body * {
                visibility: hidden;
                height: auto;
            }

            /*Setting selected elements and their children to be visible*/
            .section-to-print-head, .section-to-print-body, .section-to-print-head *, .section-to-print-body * {
                visibility: visible;
                page-break-after: avoid;
            }

            /*Positioning the head section*/
            .section-to-print-head {
                position: fixed;
                left: 0;
                top: 0;
                width: 100%;
            }

            /*Positioning the body section*/
            .section-to-print-body {
                position: fixed;
                top: 50px;
                left: 0;
                z-index: 999;
                width: 100%;
            }

            .section-to-print-body ~ * {
                z-index: 0;
                display: none;
            }
        }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it necessary to have col-xs-12 in Bootstrap 3?

In order to achieve the desired display for different screen sizes, we have implemented the following code: <div class="col-md-6">left</div> <div class="col-md-6">right</div> When viewed on smaller screens than md, this code succe ...

display a dual-column list using ngFor in Angular

I encountered a situation where I needed to display data from an object response in 2 columns. The catch is that the number of items in the data can vary, with odd and even numbers. To illustrate, let's assume I have 5 data items to display using 2 co ...

Packages have gone astray post node_modules scrub

I encountered an issue with npm run watch getting stuck at 10%, so I took the step of deleting the node_modules directory and package-lock.json. However, it seems that I may have installed modules using npm install without the --save-dev option. Even after ...

Angular 5 arrays within arrays

I'm currently facing an issue with using ngFor on a nested JSON output. The outer loop is working as expected, but the inner loop is not functioning properly. Below is my code snippet: Typescript file import { Component, OnInit } from '@angula ...

Exploring jQuery's parent selector for traversing the DOM

I am currently working with an array that inserts articles into my website. I have a specific requirement where, upon clicking the title (h3), I need to display more information based on the article's index. To achieve this, I believe I should travers ...

jQuery can be used to relocate buttons on a webpage

When the Contact button is clicked, how can I move the Close button below #panel? It's currently fixed in position. Here's my demonstration: https://jsfiddle.net/25u78gff/ jQuery('.sub-menu').addClass('dropdown-menu'); jQ ...

Prevent the loading of a <img> element and replace it with a new one using CSS

Is there a way to hide an <img> element without accessing the HTML directly, only by using CSS? The <img> element does not have any specific class. Here is the HTML markup: <img title="Manual" id="imgAjuda" src="images/ico_aj.png" width=" ...

Accessing and displaying a randomly selected PDF file from a directory using HTML coding

Welcome to my recipe collection website where I document all the delicious recipes I love to eat. One feature I would like to add is a 'random' button, so that a recipe will be selected at random for me without having to make a decision. Althou ...

Guide on setting an attribute value with JavaScriptExecutor in Selenium WebDriver

I am attempting to set an attribute value for all instances of the same type of <img> tag on My website, for example: <img src="images/temp/advertisement.png"> and I want to set style="display: none" so that I can hide them. I have tried the ...

Squashing the `require()` method in nwJS using emberJS

I am facing an issue with my nwjs application that connects to a web address hosting an ember application. I need to access the node context within the ember application to determine the user's operating system for updating purposes. I attempted to do ...

Make the div disappear after a specified time

Does anyone know of a code snippet that can make a couple of div elements fade out after a specific time period? Currently, I have the following example: <div id="CoverPop-cover" class="splash"> <div id="CoverPop-content" class="splash-center"> ...

triggering php object on mouse hover

I'm currently working on creating a mouseover effect for my PHP elements within a store. My goal is to have a transparent div appear over the dynamically generated PHP sections. I have set it to display block mode to test its functionality and positio ...

Display a complete calendar with the date picker on a webpage

Currently experimenting with React to build a straightforward application. Admiring the appearance of full calendars from these date pickers (once clicked): Material-UI React-Toolbox Wondering if it's feasible to present the full calendar directly ...

Transferring information to a function

I'm looking for a way to pass the variable Date to my function HasBtnRights(). Does anyone have suggestions on how I can achieve this? <asp:TemplateField HeaderText="More info" Visible='<%#HasBtnRights(Eval("Date")) %>'> < ...

What scenarios call for the utilization of setScriptTimeout?

When using Selenium WebDriver, there is a method called setScriptTimeout(time, unit). The description of this method states that it Specifies the time allowed for an asynchronous script to finish executing before an error is thrown. If the timeout is set ...

Align both the image and text in the center with no space between

How can I center two blocks containing both images and text vertically and horizontally while using flexbox? I notice that when the text is longer, padding appears between the image and the text. How can I remove this padding?1 .product-teaser { width ...

What is the method for transforming a JavaScript array (without an object name) into JSON format (with an object name)?

Currently, I am using an ajax query to read a local csv file and then loading the extracted values into an array. This is how the string value appears in the csv file: "Tiger","Architect","800","DRP","5421" ...

Add Django template without adding an extra line break

In my main.html template, I have the following code: <p>{% include "pouac.html" %}{% include "pouac.html" %}</p> The file pouac.html contains just one line: <span>pouac</span> When rendered, the main.html template generates two ...

What is the best way to place an "Add row" button directly in front of every horizontal row border within a table?

I would like to create an HTML table where I can insert rows by clicking on a centered "insert row" button placed between each pair of rows. This will help in visually indicating where the new row will be added. Is there a CSS solution to achieve this lay ...

Transforming JSON/XML into a hierarchical display

I've come across the following XML file: <Person attribute1="value1" attribute2="value2"> value3 <Address street="value4" city="value5">value6</Address> <Phone number="value7" type="value8">value9</Phone> </Pers ...