1

How do I conditionally apply a @media print css ruleset ONLY when a certain div is present on the page.

I have the following css which helps when printing #mytargetdiv:

@media print {
    .inside-article > :not(#mytargetdiv), .inside-navigation, .site-footer {
        display: none;
    }
}

It works great, except that some pages have #mytargetdiv and some do not contain a div with that id. If a div with the id #mytargetdiv is NOT present on the given page, then I do not want to apply this @media print rule.

How do I exclude this @media print css rule on pages that do not contain #mytargetdiv.

l_r
  • 173
  • 9
  • hi, will the rule apply to descendants/siblings of the target div? this might be of interest https://stackoverflow.com/questions/29037763/css-equivalent-of-has/29037846 – jspcal Sep 22 '21 at 23:59
  • 1
    You will have to detect that with javascript then perhaps add a class to the body to signify that. You cannot do this with css alone – Huangism Sep 22 '21 at 23:59

1 Answers1

1

You can check for existence of the id using Javascript, then add the styling if it is found.

if (document.getElementById('mytargetdiv') != null) {
    var style = document.createElement('style');
    style.innerHTML = '@media print { .inside-article > :not(#mytargetdiv), .inside-navigation, .site-footer { display: none; } }';
    document.body.appendChild(style);
}
George Sun
  • 968
  • 8
  • 21
  • Interesting. Too bad .css alone can't handle this. Using the logic you're showing with javascript, I guess in my php code I could conditionally insert the style tag only on the pages that require it (i.e. those that I know will contain #mytargetdiv). – l_r Sep 23 '21 at 00:07
  • I was able to get it to work by conditionally inserting the @media print style rule via php only on pages that I know contain #mytargetdiv. – l_r Sep 23 '21 at 00:22