How to add a print button to a web page

How to add a print button to a web page

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Targeted Printing with CSS Print Media Queries

The fundamental challenge in printing specific portions of a webpage lies in understanding that the browser's print engine does not natively support "printing buttons" that trigger partial rendering based on DOM elements alone. When you click the standard browser print icon or use window.print(), the browser attempts to render the entire document as it exists in memory. To achieve selective printing—such as printing a table without its graphs, or vice versa—you must manipulate how the browser perceives the layout specifically for the print medium.

The most robust solution involves leveraging CSS @media print rules combined with JavaScript event handling. This approach separates the visual styling of the screen from the structural requirements of the printed page. On the screen, you might want all elements visible and interactive. In the print stylesheet, you can hide unwanted elements and adjust margins or headers for the specific sections you intend to include.

The core mechanism relies on toggling classes on the target elements when a print action is initiated. Consider a layout containing a data table followed by two charts. To create a button that prints only the table, you first assign a unique class to the table container, perhaps print-target-table. Similarly, the container holding both graphs receives a class like print-target-graphs.

When the user clicks the "Print Table" button, JavaScript should execute a function that performs two critical steps. First, it must hide all elements that are not part of the intended print job. This is often done by adding a CSS class, such as .no-print, to every element except the one you wish to keep, or by directly setting display: none on the unwanted sections before triggering the print dialog. Second, the script calls the browser's native print function via window.print().

Here is a conceptual implementation using vanilla JavaScript and HTML attributes:

<style>
  /* Screen styles */
  .table-section, .graph-section { display: block; margin-bottom: 2rem; }
  
  /* Print styles */
  @media print {
    /* By default, hide everything we don't want in the specific print view */
    .print-only-table ~ *, 
    .print-only-graphs ~ * {
      display: none !important;
    }
    
    /* Ensure the target element has correct page breaks if needed */
    @page { margin: 1cm; }
  }
</style>

<div id="table-section" class="print-target-table">
  <!-- Table content -->
</div>

<div id="graph-section" class="print-target-graphs">
  <!-- Graph content -->
</div>

<button onclick="printTable()">Print Table Only</button>
<button onclick="printGraphs()">Print Graphs Only</button>

<script>
function printTable() {
  // Hide everything except the table section
  const allElements = document.querySelectorAll('*');
  allElements.forEach(el => {
    if (!el.closest('#table-section')) {
      el.style.display = 'none';
    }
  });
  
  window.print();
}

function printGraphs() {
  // Hide everything except the graph section
  const allElements = document.querySelectorAll('*');
  allElements.forEach(el => {
    if (!el.closest('#graph-section')) {
      el.style.display = 'none';
    }
  });
  
  window.print();
}
</script>

While this method works, it has a significant drawback: the DOM is modified during the print action. If the user navigates away or refreshes before closing the print dialog, the changes are lost. Furthermore, some browsers may struggle with elements that are hidden via display: none when calculating page breaks, potentially leading to awkward layout issues where the target content starts in the middle of a page unexpectedly.

A more elegant architectural pattern involves using CSS classes controlled by data attributes rather than inline styles or direct DOM manipulation within the print function. You can define specific classes like .print-table-only and .print-graphs-only. The buttons simply toggle these classes on their respective containers before calling window.print().

@media print {
  .print-graphs-only { display: none; }
  .print-table-only ~ * { display: none; } /* Adjust selector based on actual DOM structure */
  
  /* Optional: Reset margins for the visible area to fit standard paper */
  @page { size: A4; margin: 2cm; }
}

The trade-off here is complexity in CSS selectors versus simplicity in JavaScript. If your layout is deep or nested, writing a selector that excludes everything except one specific region can become brittle. In such cases, assigning unique IDs to the containers you want to print and targeting those IDs explicitly in the @media print block offers better performance and maintainability.

It is also worth noting that different browsers handle page breaks differently. Internet Explorer historically required specific hacks for @page, while modern Chrome and Firefox adhere closely to the CSS Print Media Module Level 3. If you are building a Laravel application, you can leverage Blade directives to conditionally include these print-specific stylesheets or pass data attributes from your controller logic to determine which content should be visible during the print event, ensuring separation of concerns between presentation and backend logic.

Ultimately, the goal is to give the user control over what leaves their screen without forcing them into a full-page PDF export that they then have to crop manually. By combining targeted CSS isolation with precise JavaScript triggers, you can deliver a seamless printing experience that respects the user's intent.

Our network