johnny johnny -4 years ago 119
CSS Question

Is it possible to negate an element from receiving display:none using the :not pseudo-class in CSS?

<html>
<body>
<nav>....</nav>
<article>more things...</article>
<div id="myModal" class="modal">contents</div>
<body>
</html>


In linked CSS file (using Chrome):

@media print{
body:not(#myModal){
display:none;
visibility:hidden;
}
#myModal{ /*shouldn't have to but doesn't work anyway */
display:block;
visibility:visible;
}
}


This does not work. I am trying to get rid of everything behind the modal for printing without scripting. Apparently that is not possible. Can a display:none :not not negate elements contained within the container?

Edit: I have looked here, but cannot find the answer. https://www.w3.org/TR/css3-selectors/#negation

Edit: I want to hide everything except the modal. But display:none keeps that from happening. It does it for the whole body element, regardless of my negation.

Edit: Whatever it is, it does not work in the media call, so my current idea is to move the div. I thought there might be a better way. Edit: I also need display:none because print will still print the blank pages where the elements are hidden. display will remove those elements and allow me to print my modal without a bunch of blank pages of hidden elements.

Answer Source

display: none doesn't load the element or it's children. To Chrome, Firefox, etc., #myModal doesn't exist. Consequently, you can't use display: none as the way to did.

There are other alternatives though:

Option 1

@media print {

    * {
       visibility: hidden;
       height: 0 !important; /* added !important with info from update */
    }

    #myModal {
        visibility: visible;
        height: auto !important;
    }

}
<body>
<nav>....</nav>
<article>more things...</article>
<div id="myModal" class="modal">contents</div>
<button onclick="window.print();">Print</button>
<body>

Option 2

This probably won't work with your new update.

@media print {
    body > *:not(#myModal) {
        display: none;
    }
}
<body>
<nav>....</nav>
<article>more things...</article>
<div id="myModal" class="modal">contents</div>
<button onclick="window.print();">Print</button>
<body>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download