Search code examples
htmlcssprintingmedia-queriesbootstrap-5

print only specific elements on a web page


I have read many topics about this, but still not working for me.

On my webpage I want to hide some elements when the user prints the page.

I am using Bootstrap 5, which has this in CSS:

@media print{.d-print-none{display:none!important}}

Then in HTML I just used it e.g. <div class="d-print-none">Some text</div>

But after I press CTRL+P, all the text is there ready to print.

I also created my own CSS

  @media print{
    
    .noprint{
        display: none !important;;
    }
 }

Still no luck, the elements are not hiding when trying to print them. Any suggestion?


Solution

  • so for some reason only this solution is working for me:

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

    and inside that CSS I put

    .noprint{
            display: none !important;;
        }
    

    Maybe the reason is that for all CSS links I have media="screen" and that's why inside the @media print is ignored.

    That's why using separate <link rel="stylesheet" href="print.css" media="print" /> probably works.