简体   繁体   中英

How can i apply CSS to print?

I am trying to print a div in one of my pages but i can't apply css when printing. Writing media="print" inside of the style tags doesn't work. What should i do?

   <style type="text/css" media="print">
body
{
font-size:medium;
color:Black;
font-size:14px;
}
input 
{
margin:0px;
font-size:14px;


}
.grid
{
border-color:Gray;
border-width:1px;

}
.alan
{
border-style:none;

}

.grid1
{
border-color:Gray;
border-width:1px;
}
    </style>

Use the following:

<style type="text/css">
    @media print
    {
        body {
            /* styles */
        }
    }
</style>

There is many ways for that:

First: <style type="text/css"media="print">

Second: <style type="text/css"media="screen">

Third:

@media print 
 {
 body { margin: 0; background-image: none; font-size: 12pt; }
 }

Hope this is Helpful for you..

What you're doing in your original message will work fine. It's just the old school way of doing things.

One thing to note is that the browser will not apply all of your styles in the print mode. It picks and chooses which styles are print appropriate. I have also found that if you use a HTML 5 doctype it will give you slightly different results.

Here's a simple example similar to yours that you can try in the browser.

<!DOCTYPE html>
<html>
<head>
<style media="print">
.hideForPrint { display:none; }
.anotherSTyle { font-family: Verdana; text-decoration:underline; }
</style>
</head>
<body>
<div class="hideForPrint">Print This?</div>
<div class="anotherStyle">Another Style</div>
</body>
</html>

Here's a screenshot from the print preview of Chrome (v19.0.1077.3 canary), which you mentioned your using to test this.

在此处输入图片说明

I'm using the Jquery Print Element 1.2 plugin to print only the content of a div. This way, you don't need to set css display:none for all those elements you don't want to print.

I know it's not a straight answer on your question, but see it as a kind suggestion.

Example:

$('SelectorToPrint').printElement();

Here's my implementation using the classNameToAdd option:

function printDiv(divToPrint) {

   $('#' + divToPrint).printElement(
        {
            printBodyOptions:
            {
                classNameToAdd: 'printarea'

            }
        }
   );

}

Once you've added the plugin to your page you can call the above function when the users clicks the print button/link.

<a href="#" onclick="javascript:printDiv('theIDofYourDiv')">Print part of the page</a>

You can download this plugin and find more documentation here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM