Ensure tables are vertically centered when printing an HTML page

I need to export two tables, each measuring 7cm×15cm, to a PDF file with A4 portrait paper size using the browser's "Save to PDF" option in the print tool.

My goal is to center these two tables vertically on the A4 paper. If that proves difficult, I would like them positioned at the same location on the page.

Currently, the tables are not placed exactly where I want them on the page (as shown in the image below).

The HTML code for the tables is as follows:

<body>
<!-- 1st table -->
<table>
<tr> <td>content of the first table</td>
<!-- additional tr's and td's -->
</tr>
</table>
<!-- 2nd table -->
<table>
<tr> <td>content of the second table</td>
<!-- additional tr's and td's -->
</tr>
</table>

</body>

Along with the following CSS rules:

table {width:7cm; height:15cm; border: 1px solid;
  page-break-after: always;
  margin: auto;
  }
@media print {
  @page { size: A4 portrait; }
  }

The page-break-after: always; rule tells the browser to insert a page break after each table.

The margin: auto; rule horizontally aligns the tables on the page.

I require both tables to be printed on the same paper for a two-sided printing setup.

Current Output:

https://i.stack.imgur.com/3kTKq.png

Any assistance or suggestions would be greatly appreciated!

Answer №1

After some experimentation, I managed to come up with a solution that doesn't rely on javascript. Simply adjust your media settings for print like so:

@media print {
    body {margin-top:0 !important;}
  @page { size: A4 portrait; }

  }

To ensure the tables are centered properly, you'll need to enclose them in a div wrapper as shown below:

<body>
    <!-- 1st table: -->
    <div class="page">
    <table>
    <tr> <td>content of the first table</td>
    <!-- additional tr's and td's -->
    </tr>
    </table>
  </div>
    <!-- 2nd table: -->
    <div class="page">

    <table>
    <tr> <td>content of the second table</td>
    <!-- additional tr's and td's -->
    </tr>
    </table>
    </div>
    </body>

Lastly, don't forget to add these CSS rules for flex display:

@media print {
    body {margin-top:0 !important;}
    .page{
      height: 100vh;
      width: 100vw;
      display: flex;
      align-items: center;
      justify-content: center;
    }

  @page { 
    size: A4 portrait;
  }
  }

Following these steps should result in proper centering of your content.

Answer №2

[Advice]:

Hey @tush, I totally agree with your suggestion in the comments. If we have the height measurements for both the element and the container (body), we can manually position them using margin: 6cm auto;. Take a look at the example below.

[Outcome]:

PDF file perfectly centered

[Code Snippet]:

table {width:7cm; height:15cm; border: 1px solid;
  page-break-after: always;
  margin: 6cm auto;
  }
@media print {
  @page { size: A4 portrait; }
  }
<body>
<!-- 1st table: -->
<table>
<tr> <td>content of the first table</td>
<!-- some other tr's and td's -->
</tr>
</table>
<!-- 2nd table: -->
<table>
<tr> <td>content of the second table</td>
<!-- some other tr's and td's -->
</tr>
</table>

</body>

Answer №3

Here is a potential solution that centers the objects perfectly using a simple addition of a transform trick within your provided HTML and CSS:

<html><head>
    <title>Two Centered Tables</title>
    <style>
        table {
                width: 7cm;
                height: 15cm;
                border: 1px solid;
                page-break-after: always;
                margin: 50%;
                transform: translate(-50%, -50%);
                text-align: center;
        }

        @media print {
                @page {
                        size: A4 portrait;
                }

        }
    </style>
</head>
<body>

        <!-- 1st table: -->
        <table>
            <tbody>
                <tr>
                    <td>content of the first table</td>
                    <!-- some other tr's and td's -->
                </tr>
            </tbody>
        </table>
        <!-- 2nd table: -->
        <table>
            <tbody>
                <tr>
                    <td>content of the second table</td>
                    <!-- some other tr's and td's -->
                </tr>
            </tbody>
        </table>


</body></html>

Displayed in Chrome DevTools

https://i.stack.imgur.com/ZfoLw.png

Utilize ctrl/cmd-P to access the print dialogue easily.

By setting up two pages per sheet for demonstration, you can witness the precise alignment. During actual printing, revert back to one page per sheet (default). Opt for no margins (although auto will suffice); with background graphics and header not selected. https://i.stack.imgur.com/z9KAP.png

<!DOCTYPE html>
<html>
<head>
    <title>Two Centered Tables</title>
    <style>
        table {
                width: 7cm;
                height: 15cm;
                border: 1px solid;
                page-break-after: always;
                margin: 50% 50% 50% 50%;
                transform: translate(-50%, -50%);
                text-align: center;
        }

        @media print {
                @page {
                        size: A4 portrait;
                }

        }
    </style>
</head>
<body>
    <div style="display: grid;">
        <!-- 1st table: -->
        <table>
            <tbody>
                <tr>
                    <td>content of the first table</td>
                    <!-- some other tr's and td's -->
                </tr>
            </tbody>
        </table>
        <!-- 2nd table: -->
        <table>
            <tbody>
                <tr>
                    <td>content of the second table</td>
                    <!-- some other tr's and td's -->
                </tr>
            </tbody>
        </table>
    </div>
</body>
</html>

Execute this code snippet, ensure to view in full screen (click "Full Page" after running → not "Extend snippet"), then proceed with printing as depicted here: https://i.stack.imgur.com/loic2.png Again, just for verification (showing 2 per page for alignment check): https://i.stack.imgur.com/nJJw9.png

If there were issues with the hard-coded dimensions in centimeters impacting the display on your monitor, it could be due to conflicting sizes based on different monitors. Anyone have insights on this?

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

Revamp every single hyperlink that ends in .html

I am looking to customize the URLs on my website to appear like this: www.example.html/1 www.example.html/2 www.example.html/3 instead of their current format: www.example.html/1.html www.example.html/2.html www.example.html/3.html Can anyone provide a ...

Uploading files via an HTML form

I am facing an issue while attempting to save a file uploaded from a form. Despite following the tutorial on the w3schools website, I keep encountering an error stating 'Undefined index: userpic' in C:\wamp\www\HW4\confirm.php ...

Customize the initial color of the text field in Material UI

I am currently working with the mui TextField component and facing an issue. I am able to change the color when it is focused using the theme, but I cannot find a way to adjust its color (label and border) in its initial state when it's not focused. I ...

Utilizing D3.js: Applying Multiple Classes with Functions

My current project involves using D3.js and I've encountered a particular challenge that has me stumped. In the CSV file I'm working with, there are columns labeled "Set" and "Year". My goal is to extract values from these columns and use them a ...

Enhancing Dropdown Functionality Using Jquery

Hey there, I am looking to create a dropdown list/menu similar to the one shown in this image: (a screenshot). Could you please guide me on how to achieve this? Can it be done using JQUERY? Thank you in advance, Andrea ...

Enhancing audio control features using HTML and JavaScript

After utilizing various suggestions, I have successfully created a basic audio slider that starts playing sound (at zero volume) when clicked by the user. They can then adjust the volume as needed. My only challenge is that the volume adjustment only occu ...

How can the 'Read more' feature be modified to impact multiple boxes? (Using jQuery, JS, and CSS)

I am trying to add a 'Read more' feature on my friend's website. I was able to achieve the desired effect, but when I tried to adjust the alignment of the box, it affected the 'Read more' feature. Original design: https://codepen. ...

Support for the percent sign in right-to-left languages

Imagine you have the following code snippet: <div dir="rtl"> test 50% </div> It currently displays as test 50%. However, according to this wiki page, for Arabic language it should be shown as %50 test, with the percentage sign before the n ...

Executing a C# function from an HTML hyperlink

I am in the process of developing a website using ASP.NET C#. The site will feature a GridView with data that can be exported, such as to Excel or other formats. To handle the export functionality, I plan to utilize code from this resource. When a user c ...

Center alignment is not being applied to the SVG element

I am currently working with React and when my component renders, it displays an SVG inside a div. Here is a snippet of the code: render() { return( <div class="myClass"> <svg> ... </svg> </div> ); ...

What is the best way to ensure a footer always remains at the bottom of the page with Telerik controls?

I'm currently working on an asp.net MVC project that utilizes the latest version of Telerik controls. The layout consists of a shared view with a header at the top, a left-side menu, and a footer at the bottom. In the main section, I use a @RenderBody ...

Changing the structure of divs by using elements from different divs

I'm looking for some help with adjusting the CSS of a div when hovering over certain elements. Here is my current code: <div class = "container-main"> <div class = "container-inner"> <ul class = "list"> &l ...

Is there a way to assign the scroll event context to `document.body` instead of `window`?

Discovery As I delved into the intricacies of web development, I stumbled upon a curious observation. In a particular MDN page, I noticed that the left and right sidebars had their scrollbars contained within themselves. However, the content block's ...

Vuetify's offset feature seems to be malfunctioning as it does not

I'm facing an issue with the <v-flex> element in my code, specifically with the offset property not responding as expected. Despite following the recommended layout from the vuetify docs, I can't seem to get it right. Below you can see the ...

Setting a minimum height for bars on a graph can be achieved by adjusting the

I need assistance with my graph display. Currently, the graphs are not showing when the value is less than a certain point. I would like to set a minimum height so that they can be displayed regardless of the value. My graphs are being generated using cha ...

Alter the website link in an HTML file as well as in the corresponding CSS and JavaScript

Is it possible for JQuery to alter URLs within a CSS or Javascript resource before they are loaded into the browser, or even as they load in the browser? URLs typically point to resources such as images and fonts. I have been considering this idea becaus ...

Using jQuery to access specific elements within the DOM by navigating through the document structure

I'm currently facing a challenge with using jquery's parents/siblings functions to locate specific input elements. Despite my efforts, I can't seem to get it right. Here is the HTML structure I am working with: <div id="ExtrasOptions"&g ...

Triggering a system context menu through a longpress gesture on the MobileFirst iOS app is a

After experimenting with our MobileFirst iOS app, I noticed that if you hold down on any anchor links for more than 2 or 3 seconds, iOS will bring up a built-in menu displaying the internal path of the current HTML page. I'm unsure whether this behav ...

Are custom boolean attributes supported in HTML?

When working in HTML5, we have the ability to utilize custom data-* attributes. However, since these are considered attributes, they generally require a string value. Is there a different option within HTML that allows for custom properties, where boolean ...

What could be the reason that my d3.tooltip is not functioning properly for these specific two lines on the chart?

I am currently experiencing issues with the d3.tool tip for my line charts. Additionally, I would like to adjust the y-axis scale to create larger gaps between the lines. Below are the codes used to generate the line charts: <!DOCTYPE html> <meta ...