Valkyrurr
Valkyrurr

Reputation: 119

css for media print

Ok, so I have this code:

HTML:

<body>
    <div>...</div>
    <table id="printthis">
        <tr>
            <td>...</td>
            ...
            ...
        </tr>
    </table>
    <someOtherElementIdontNeed />
    <div>...</div>
</body>  

CSS:

@media print {
    body *:not(.printable) {
        display: none;
    }
    .printable {
        position: absolute;
        top: 0;
        left: 0;
    }
}  

JS: (I have somewhere in the HTML that triggers this(to print))

jQuery(document).ready(function(){
    jQuery("#print").click(function(event){
        jQuery("#printthis").addClass("printable");
        jQuery("#printthis *").addClass("printable");
        window.print();
    });
});  

Basically, I want all the contents of the <table> be printed except everything else that is not inside the tag. I triggered a jQuery.addClass to distinguish whatever is printable from what is not.

JS script seems to be working fine, I checked through chrome dev tool, its being appended. My css just don't seem to recognize them.

Isn't this what's suppose the :not() selector is designed to handle? When print is triggered, all I'm getting is a blank page... displaying all elements as none which doesn't exempt those with .printable class

Upvotes: 0

Views: 6085

Answers (2)

Mihai T
Mihai T

Reputation: 17687

see here jsfiddle

DO NOT use same ids (#printthis) use classes instead .printthis
you cannot have duplicate id-s only classes. that's why it doesn't work for you but it works only in this example where there is a single #printthis id

ALSO . be careful not to have an element that you want to print..inside another element that doesn't have the class .printthis

for eg do not use

 <div>
    <div class="printthis"> PRINT ME </div>
</div>

after adding the .printable class with JQ to all the elements with .printthis, the code from

@media print {
 body *:not(.printable) { display:none }
}

will hide the parent element and so any child of that element won't be visible when you print

UPDATED JS CODE

 jQuery("#print").click(function(event){
    jQuery(".printthis").addClass("printable");
    jQuery(".printthis *").addClass("printable");
    window.print();
});

UPDATED html :

<body>
<div>DO NOT PRINT</div>
<table class="printthis">
    <tr>
        <td>SHOW</td>
        SHOW
        SHOW
    </tr>
</table>
<div class="printthis">TESTPRINT</div>
<someOtherElementIdontNeed />
<div>DO NOT PRINT</div>
<button id="print"> PRINT</button>
</body>  

Css :

@media print {
body *:not(.printable) {
    display: none;
}
.printable {
    position: absolute;
    top: 0;
    left: 0;
}
}  

Upvotes: 2

user3154108
user3154108

Reputation: 1294

try

@media print {
    body *:not(.printable, .printable *) {
    display: none;
    }
    .printable {
        position: absolute;
        top: 0;
        left: 0;
    }
}  

Upvotes: 1

Related Questions