Use CSS to hide contents on print

后端 未结 5 1662
萌比男神i
萌比男神i 2020-12-15 09:07

I’m looking for an easy way to hide everything except a certain div and its contents.


  
  
    
相关标签:
5条回答
  • 2020-12-15 09:33

    Assign a separate CSS file that defines the behaviour when printing a web page.

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

    and then within that file just define:

    .header, .menu, .footer { display: none; }
    
    0 讨论(0)
  • 2020-12-15 09:35

    I did it css3 way: using not pseudo class and direct ancestors (children)

    /* hide all children of body that are not #container */
    body > *:not(#container) {
      display: none;
    }
    /* hide all children of #container that are not #content */
    #container > *:not(#content) {
      display: none;
    }
    /* and so on, until you reach a div that you want to print */
    #content > *:not(#print_me) {
      display: none;
    }
    

    This way you can eliminate everything except what you want to print even in very complex layouts. :not is very efficient here because it takes care about any future modifications of you html.

    0 讨论(0)
  • 2020-12-15 09:36

    Depending on your HTML structure (and browsers you need to support, because IE6 won't support this), you could hide all top-level divs and just show the one/few you want to show:

    body > div {
       display: none;
    }
    
    #content {
      display: block;
    }
    
    0 讨论(0)
  • 2020-12-15 09:41
    @media print {
    .noPrint {
        display:none;
      }
    }
    

    Now you need to apply the class noPrint to the elements you want to hide in printing.


    It is good practice to use a style sheet specifically for printing, and and set it's media attribute to print.

    Example:

    <link rel="stylesheet" type="text/css" href="print.css" media="print" />
    
    0 讨论(0)
  • 2020-12-15 09:58

    You can use classes.

    .classHide{display: none}
    

    Depending on the language you are using, when if==true you can add a class to header, menu and footer.

    So you won't need to use another css file.

    0 讨论(0)
提交回复
热议问题