0

How to create a print stylesheet which can override the dynamic styles created by css modules ?

Using CSS modules, classnames render with unique names like so :

<button class="buttons_style_primary-button__3T" type="submit"> Submit</button>

In my print stylesheet I have the following, which has no effect :

@media print {
  button {
    display: none;
  }
}

I can get it to work by adding !important to the button style, but I will have many print styles and I don't want to do this for each style attribute. Is there an alternative ?

I'm also using React if there happens to be a React specific approach here.

looshi
  • 1,226
  • 2
  • 9
  • 23

2 Answers2

1

Wound up doing the following :

Use !important for globals that need to override local values:

/* app.css */
@media print {
  @page {
    margin: 1cm;
  }

  * {
    color: #000 !important;
  }
}

Put component specific overrides into a style.css for each component:

/* style.css */
.my-class {
  composes: rounded-corners from 'shared/ui.css';
  margin: 0 0 60px 0;
  background-color: white;
}

@media print {
  .my-class {
    page-break-inside: avoid;
    font-size: 10px;
  }
}

/* my-component.jsx */
import style from './style.css';

const MyComponent = () => {
  return (
    <div className={style.myClass}>
      ....
    </Link>
  );
};

There's also a third option which I haven't really tried.

You should be able to apply both the top-level override classname with your local classname using the classNames library:

import app from 'app.css';
import styles from './style.ss'
const MyComponent = () => {
  return (
    <div className={classNames(style.local, app.global)}>
      ....
    </Link>
  );
};

( this third option is just off the top of my head, I don't know if it will work )

looshi
  • 1,226
  • 2
  • 9
  • 23
0

Instead of this:

@media print {
  .button {
    display: none;
  }
}

Try this:

.button{
  @media print {
    display: none;
  }
}
Qui-Gon Jinn
  • 3,722
  • 3
  • 25
  • 32