简体   繁体   中英

How can I override an inline CSS rule using an external file?

How can I override an inline CSS rule with using an external stylesheet file?

This is my HTML code:

<div class="mydiv" style="background:#000"> lorem ipsom</div>

I want to change the background color using CSS. This is my CSS code:

.mydiv {background:#f00; color: #000;}

But this is not working, but I this is possible.

Is there a way to change the background color in Internet Explorer?

Inline style is treated as having a higher specificity than any rule-set.

The only ways to override it are to change it on the element or use an !important rule .

!important rules are a sledgehammer of a solution and only work once (if you want to override again, you are stuck; there is no such thing as a double !important rule), so changing the style attribute value (preferably removing it entirely in favour of a stylesheet) is the best option.

If you really want to use !important then the syntax is:

.mydiv {
    background:#f00 !important;
    color: #000;
}

This is very simple. Use !important after your rule style. Here is the example:

.mydiv {background:#f00 !important; color: #000;}

URL: http://jsfiddle.net/msJxL/

And for Internet Explorer, check out How To Create an IE-Only Stylesheet | CSS-Tricks .

Use the !important for this. It will override other CSS. Try the following code:

.mydiv {background:#f00 !important; color: #000;}

Use this:

.mydiv {
     background: #f00 !important;
     /* This will increase the rule score */
     color: #000;
}

Detailed information: Stack Overflow question How can I override inline styles with external CSS? .

You can use the CSS attribute selector:

 <style>
     div[style] {
        background: blue !important;
     }
 </style>

 <div style="background: red;">
     The inline styles.
 </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM