Jay
Jay

Reputation: 707

how can i add a css file to body of a page?

I am working on a page which has a print view so when the user clicks on "Print" a new window pops up and I want to add a .css file just for that window.

Thanks

Upvotes: 0

Views: 1078

Answers (4)

Adam Terlson
Adam Terlson

Reputation: 12730

EDIT: Removed due to clarification. New answer:

Open the URL in a new window as such: blah.aspx?print=true

Then on your backend:

//Assuming you use .NET...
if(Request.Querystring("print").toLower() == "true" ) { //Convert to bool type if you are so inclined
   printCSS.Visible = True;
}

HTML:

<head>
    <link rel="stylesheet" type="text/css" href="..." visible="false" runat="server" id="printCSS" />
</head>

You could also use one of the jQuery methods shown to load it in using jQuery too.

Upvotes: 1

rfadams
rfadams

Reputation: 1978

You can add a print only style sheet

<link rel="stylesheet"  type="text/css"  media="print" href="print.css" />

This stylesheet does not need to be "added" to popup windows. It will be ignored when the user is in the "normal" view and then only applied when the user goes to print the document.

If you want to be both visible and apply to the printed document, just have it cascade.

<link rel="stylesheet"  type="text/css" href="normal.css" /> #normal styling
<link rel="stylesheet"  type="text/css" href="print.css" /> #override normal styling
<link rel="stylesheet"  type="text/css"  media="print" href="print.css" /> #override normal, for printer

That way you get the best of both worlds. Override the css rules in normal.css with new rules in print.css, as needed to make the document look as you wish. The new document will visually look different and then also print out differently.

Upvotes: 5

Rafael Herscovici
Rafael Herscovici

Reputation: 17094

$(document).ready(function () {
    $(".print").click(function () {
        $("head").append("<link>");
        css = $("head").children(":last");
        css.attr({
            rel: "stylesheet",
            type: "text/css",
            href: "css/ecsPrint.css"
        });
        return false;
    });
});

Unless this is a Internal Web Application, i wouldnt recommend loading css with JS.

Upvotes: 0

Michael Rose
Michael Rose

Reputation: 7820

When including your stylesheet, use this:

<link rel="stylesheet" media="print" href="stylesheet.css" />

Upvotes: 6

Related Questions