Set CSS according to browser

Asked

Viewed 9,393 times

5

I found a command to change CSS in Firefox:

@-moz-document url-prefix() {
    body {
        background: #f00;
    }
}

This command will put a red background only in firefox, for example.

I found it very useful, but I wonder if there is a way to do this with other browsers, but in this style, without the use of "<!--[if IE 8]>" for example.

3 answers

6


Yes it is possible, this "technique" has a name: CSS Hack, basically it abuses the rendering errors of the browsers, because they are properties written in a wrong way just to not work but the browsers interpret as valid instruction, for example:

#teste {
    background-color: Red;
    _background-color: Black; // No IE o fundo ficará com a cor preta
}

There are several CSS Hacks, when you need any specific I recommend the site Browserhacks for consultation.

The passage you posted <!--[if IE 8]>, is a conditional comment: "Conditional comments are comments included in the HTML code written exclusively to make a part of the code work in Internet Explorer.", source.

1

Simple:

  • -moz is for Firefox
  • -ms for Internet Explorer
  • -o for Opera <= 12 (before adopting Webkit as the engine)
  • -webkit for browsers that use the Webkit engine like Chrome, Safari and many mobile browsers like Android itself

Behold:

(1) (2)

Updating

As @NULL said, this works only for CSS3 properties. Depending on the case it may be enough.

A more POG alternative would be to identify the browser by Javascript and then load the CSS dynamically (see).

  • Buddy, what you posted are prefixes to use the new CSS3 properties in different browsers. Fountain.

  • That’s not what he wants (different properties for different browsers)?

  • But your example only works for the new CSS3 properties, try using for example: -moz-background-color: red;, did not change the background color only in firefox right? (Actually did not change the color in any). Your comment is valid only for new properties.

  • OK. Thanks for the correction. I will edit the answer to make it clear. =)

0

According to the W3C

The rule '@document' a group rule whose condition depends on the URL of the document being formatted. This allows style sheets, especially user style sheets, to have styles that apply only to a set of pages, instead of all pages that use the style sheet.

This way you can use the prefixes to apply style specifically to a browser and some .
To define the rule of you can use the following properties:

  • url
  • url-prefix(<string>)
  • Domain(<string>)
  • regexp(<string>)

See in Document queries: the ː@Document' Rule how to use each of these properties.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.