Search code examples
cssfirefoxbrowser-detection

Targeting only Firefox with CSS


Using conditional comments it is easy to target Internet Explorer with browser-specific CSS rules:

<!--[if IE 6]>
...include IE6-specific stylesheet here...
<![endif]-->

Sometimes it is the Gecko engine (Firefox) that misbehaves. What would be best way to target only Firefox with your CSS rules and not a single other browser? That is, not only should Internet Explorer ignore the Firefox-only rules, but also WebKit and Opera should.

Note: I'm looking for a 'clean' solution. Using a JavaScript browser sniffer to add a 'firefox' class to my HTML does not qualify as clean in my opinion. I would rather like to see something that depends on browser capabilities, much like conditional comments are only 'special' to IE…


Solution

  • This solution does not rely on JavaScript being turned on.

    @-moz-document url-prefix() {
      h1 {
        color: red;
      }
    }
    <h1>This should be red in FF</h1>

    This is based on a Mozilla-specific CSS extension. Like most of these, it is deprecated. However, this extension's deprecation has an exception specifically for browser detection. The Firefox note in @document § browser compatibility states that Firefox 61+ "only supports an empty url-prefix() value, which is supported due to its use in Firefox browser detection. Still supported in user stylesheets."

    For more information about this specific CSS extension, see What does @-moz-document url-prefix() do?