Setting A4 paper size with CSS and HTML

Setting A4 Paper Size with CSS and HTML

Setting A4 Paper Size with CSS and HTMLIn web design, sometimes we need to render web content in A4 size for better printing or PDF viewing. This article will detail how to set the A4 paper size using CSS and HTML.

What is A4 Paper Size?

A4 paper is an ISO international standard paper size measuring 210mm x 297mm. When designing a web page, setting the content to A4 size ensures a consistent and aesthetically pleasing display across different devices.


Using CSS to Set the A4 Paper Size

First, we need to include a CSS file in the HTML file and set the A4 paper size style.

<style> 
@page { 
size: A4; 
margin: 0; 
} 

html, body { 
width: 210mm; 
height: 297mm; 
margin: 0; 
padding: 0; 
} 

.content { 
width: 100%; 
height: 100%; 
} 
</style> 

In the CSS code above, we use @page Use the HTML rule to set the page size to A4 and set the margins to zero. Then, set the width and height of the html and body elements to 210mm and 297mm, respectively, and set the page’s inner and outer margins to zero. Finally, set the width and height of the .content element to 100% to fit the entire page.

Setting A4 Paper Size Using HTML

Next, create a div element in the HTML file to contain the content and give it a class name of content.

<div class="content">
<!-- Webpage Content -->
</div>

With the above HTML structure, we place the content within a div element named content and set the CSS style for that element.

Sample Code

Let’s take a look at a complete sample code to show how to set the web page content to A4 paper size:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="UTF-8"> 
<meta http-equiv="X-UA-Compatible" content="IE=edge"> 
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 
<title>A4 Paper Size</title> 
<style> 
@page { 
size: A4; 
margin: 0; 
} 

html, body { 
width: 210mm; 
height: 297mm; 
margin: 0; 
padding: 0; 
}

.content {
width: 100%;
height: 100%;
}

h1 {
text-align: center;
}

p {
margin: 10px;
}

</style>

</head>

<body>

<div class="content">

<h1>Web Content Set to A4 Paper Size</h1>

<p>This is a sample text that shows how to render web content to A4 paper size.</p>

</div>

</body>

</html>

In the sample code above, we define a title and a paragraph of text and place them within a div element with the content class. In the CSS style, we set the title to be centered and the text to have margins.

Running Results

When we open the above sample code in a browser, we’ll see the webpage content rendered in A4 size. You can try printing the content to a PDF file or directly printing it to see the effect.

Through the above method, we can use CSS and HTML to set the A4 paper size, making the webpage content more standardized and easier to print and save.

Leave a Reply

Your email address will not be published. Required fields are marked *