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

Adjusting the height of a table cell in HTML: td without making it

Here's the issue I'm facing: I have an HTML <table> with a fixed height of 100px and no border. Inside this table, there is one row (with a 100% height) containing 5 td elements (each also with a height of 100%). Within each td, there is a ...

A guide to performing individual file testing in Quasar testing

I need to run specific test code in my Quasar project without running all tests. I've tried using the following commands, but they still run all test files. quasar test --unit jest -t "demo/demo.spec.js" quasar test --unit jest --spec "demo/demo.spec ...

Comparing JSON objects with JavaScript models: A guide

Currently I'm working with angular 2 and I have an array of data. data: MyModel[] = [ { id: 1, name: 'Name', secondName: 'SecondName' } In addition, I have created the interface MyModel: interface MyModel { id: number, nam ...

Utilizing Django framework for crafting a captivating homepage

Successfully set up the django framework and developed an app for my homepage. I added the app to the settings in the project folder and was able to get the HTML running smoothly. However, I am experiencing issues with styling as the CSS won't apply. ...

How do I resolve the jQuery error "unable to find function url.indexOf" when working with Vide?

I had previously asked a question regarding the use of the Vide plugin for playing background videos on my website, which can be found here. However, I am now encountering an error that is puzzling me: https://i.stack.imgur.com/UDFuU.png I am unsure abo ...

Mobile application showing alerts for connected devices

In the process of creating a hybrid mobile app, I'm looking to incorporate notifications in the top right corner of the application. The frontend consists of html and angularjs, while the backend utilizes spring rest web service. To convert the front ...

What is the procedure for eliminating a cookie with Javascript?

Is there a way to delete the cookie set by javascript:void(document.cookie=”PREF=ID=20b6e4c2f44943bb:U=4bf292d46faad806:TM=1249677602:LM=1257919388:S=odm0Ys-53ZueXfZG;path=/; domain=.google.com”); The code below fails to do so. javascript:void(docum ...

Unable to retrieve HTML element using Python's Selenium

Whenever I try to access a specific website using Selenium, a pesky pop-up appears and I can't seem to locate the close button to dismiss it. from selenium import webdriver from time import sleep from selenium.webdriver.common.keys import Keys import ...

Is there a way to incorporate a loading spinner into a MaterialUI DataTable without having to specify a fixed height for the parent component?

Currently, I am using a MaterialUI DataTable with the following setup: <div style = {{height: 300}}> <DataGrid loading={true} getRowHeight={() => "auto"} getEstimatedRowHeight={() => 250} ...

Problem with AngularJS factory causing issues with promises

I have a factory in AngularJS set up like this: 'use strict'; angular.module('frontRplApp') .factory('paymentService', function ($rootScope, $http, config, tools) { var urlBase = config.baseUrl; var payme ...

Adjusting the brightness of colors using JavaScript

I am looking for a way to return different color tones for a specific color using JavaScript. For example, if I have the color code #4a4a4a, I want to be able to return #494949 and #666464. If there is a package or method that can achieve this, please sugg ...

angular use ngFor directive to restrict the number of rows displayed in a table

In my angular 6 project, I am trying to limit the display to just five rows in a table using ngFor. My current code snippet is as follows: <tbody> <tr *ngFor="let item of routines; let i = index"> <td style="display: none"> ...

How can HTML text be displayed based on certain JavaScript conditions?

By modifying the style of the text, I was able to implement basic functionality for validating correct answers. However, my main query is whether it is feasible to display a specific phrase upon achieving a perfect score. Upon analyzing the provided sample ...

Discovering an npm module within an ember-cli addon component

I recently encountered an issue while using ember-browserify to locate npm modules in my ember-cli applications - it seems to not function properly for ember-cli addons. This leads me to wonder: Are there alternative methods for importing npm modules into ...

Remove elements generated by the .after method with Jquery

In my HTML file, I have a table with hard-coded column headers: <table id="debugger-table"> <tr> <th>Attribute</th> <th>Computed</th> <th>Correct</th> </tr> </table&g ...

Tips for comparing props in the ComponentDidUpdate method when dealing with a complex data structure that is connected to Redux

I have been experimenting with the new lifecycles of React v16. It works perfectly fine when comparing single keys. However, when dealing with large data structures like Arrays of objects, performing deep comparison can be quite expensive. My specific sce ...

Analyzing Date Strings Retrieved From a MySql Database

In my MySQL database, I have a relationship that stores dates as varchar along with other attributes. This is how it looks: Answers answerId answer questionId date I am working on a web application where the user can select a &apo ...

Locally hosted website failing to transfer login details to external domain

Having trouble with an ajax call that is supposed to retrieve data from a web page, but instead returns a jQuery parse Error. Even though I can access the page directly, the ajax call doesn't seem to be working and storing the result properly. Below ...

Angular 4's Panel Window: A User-Friendly Interface

Having experience with Adobe Flex, I am familiar with creating new panel windows in Action Script by using the 'new' keyword and popping them up using popups. The customization of these windows was achieved through functions provided in the Panel ...

Tips for Editing and Modifying Name and Area in a Database

I'm currently working with React to develop a full CRUD application, but I'm facing challenges in updating the names and areas of rooms within houses. Any suggestions or insights on how to achieve this would be greatly appreciated. Apologies for ...