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

Unique and responsive grid styling with CSS

Is it possible to create a responsive grid like the one shown in the image below? I attempted to use absolute positioning for all blocks, but I'm having trouble making it responsive... I should note that the styling will be generated dynamically usi ...

The conditional CSS file does not have precedence over the regular CSS file

Currently, my approach involves using conditional comments to connect to a CSS file named "IEonly.css" if the Internet Explorer version is not greater than 8. My goal is to modify certain properties in the standard CSS file. Oddly enough, IEonly.css effect ...

Ensure that the spacing between rows matches the spacing between columns

I am working on creating a 3x3 grid using Bootstrap. My goal is to have consistent spacing between the rows and columns. How can I achieve this effectively? ...

Creating a Hover Effect for DIV Elements Using Pure CSS, No JavaScript Needed

Imagine a straightforward, horizontal navigation on a website: | Home | About | Products | Contact | Impress | ... or something like that... A rectangular element is positioned above the navigation. Now, I want this rectangle to automatically shift hori ...

I possess a primary menu with several submenus, yet I am encountering difficulty accessing the submenus. My goal is to efficiently navigate and access the appropriate submenu within the main menu

I am facing an issue with my CSS where the sub menu is currently showing from the left side, but I would like it to slide up and down instead. .outer { width: 100%; text-align: center; background-color: Gray; padding-top: 20px; bord ...

How to Ensure that the Hidden Value of Select Statement in Angular is Always Displayed as Text

Is there a way to customize the top part of a dropdown menu so that it always displays a specific phrase, like 'Symbols' in this case, regardless of the option selected? Currently, the top part shows the last selected symbol, but I want it to be ...

Changing the width of an SVG path from 0 to 100% using CSS

I have an SVG design of wires that I want to animate the width from "0 to 100%", but I'm having trouble achieving this effect. It's easy to do with a div element, but not with an SVG image. Below is my code snippet: svg path { animation: f ...

Searching for a div table using XPATH in Python

Struggling to extract data from a table using Selenium in Python. Any suggestions on how to achieve this? https://i.stack.imgur.com/rPlKR.png <div class="js--property-table-body project-property-table__body"> <span aria-hidden=&quo ...

How to Retrieve Checkbox Values from Multiple Rows Using JavaScript

I have a variety of module rows that allow users to manage access rights by selecting specific options. My goal now is to extract the checked boxes from these checkboxes with the name "config{{$field->id}}". Below is the current functioning code. HTM ...

Is there a way for me to determine if a user has engaged with a form?

I'm surprised by how difficult it was to find information on this topic through Google. Currently, my struggle lies in wanting my form fields to change color based on validity only after the user has interacted with the form. I don't want invali ...

AJAX File Upload: Sequentially Queuing Multiple Files

I am a beginner in the world of Javascript and jQuery. When I try to upload multiple files through a form, only the last file gets uploaded repeatedly. My goal is to upload each file one by one using AJAX requests asynchronously. Here's how I have ...

Placeholder image for content background

Is it possible to set a background image specifically for a content placeholder? Currently, I can display a background image for the entire page, but the content placeholder covers most of the picture. I would like to set a background image for the content ...

How to align text to the right in an Android TextView using HTML

I need to display some HTML content in a TextView. I am aware that certain HTML tags are not compatible with Android, so I have turned to a third-party library to incorporate bulletpoints and numbered lists. However, I also require support for right alignm ...

Struggling to contain the image inside my div element

I'm having trouble with keeping the image inside my div element as it keeps stretching outside of it. I've tried researching for a solution but haven't been successful in finding one. Any help would be greatly appreciated! Here is the HTML/ ...

Correcting the reference to "/" (root) for assets after relocating the site to a subdirectory

I currently have a website located in the public_html directory, where all assets (images, css, js, etc) are referenced using /asset_folder/asset. The "/" at the beginning ensures that the browser starts from the root and navigates through the directories. ...

The JavaScript function modifies the value stored in the local storage

I'm in the process of developing a website that requires updating the value of my local storage when certain JavaScript functions are executed. Currently, I have this code snippet: localStorage.setItem('colorvar', '#EBDBC2'); I&ap ...

Iterating through an array with ngFor to display each item based on its index

I'm working with an ngFor loop that iterates through a list of objects known as configs and displays data for each object. In addition to the configs list, I have an array in my TypeScript file that I want to include in the display. This array always ...

What is the best way to ensure my gif shows up in the top row and spans two columns in this grid?

I am attempting to create cards with a unique design where the first row consists of 2 columns, one being a GIF that shows the card fitting into a cell with a border. However, all I see is an empty cell without any display. Below is the code snippet I am ...

How come child elements are clipped in IE versions 9 and above when using the border-radius property with a fixed value?

When applying css border-radius:[some value] to a parent element and having a fixed positioned child element, I noticed that in Internet Explorer the child element appears to be 'clipped' into the parent. However, if I use border-radius:0 in the ...

Position the image between two div containers in the center of the screen, ensuring it is responsive and does not overlap with any text

I've been working on trying to position an image between two divs on my webpage. So far, I've managed to place the image there but it's not responsive (only displays correctly at a width of 1920) and ends up overlapping the text in both divs ...