2
<style>
.bgClr{
background-color: lightgreen;
}
</style>

<link [email protected]("~/Content/css/xyz.css") rel="stylesheet" />
<div>......
<input type="text" class="bgClr" />
....</div>

Here is the code I've written in my html page. In xyz.css, I have defined the same css class like this

.bgClr{
background-color: red;
} // in xyz.css

But in result, background-color color of the control is always Red.

May I know the reason why the .bgClr of xyz.css is always taken ?

1
  • I thought this was a beginner's question worth of downvoting until I realized that I didn't know this precisely enough myself - I always thought <style> would have priority over <link> (which it does, theoretically) but today I learned that <link> will still override <style> if it is defined after the latter. +1 Commented Mar 21, 2017 at 10:20

4 Answers 4

6

Because it was attached later. If the external stylesheet is placed after the internal's, it will override all previous already defined selectors (internals or externals).

But if you have inline styles, they have the highest priority

Sign up to request clarification or add additional context in comments.

5 Comments

That's not really accurate though, is it? Let's say I have an element that is styled inline (style="background:red;") and then I add a <style> block at the end of my HTML document, trying to override that element, the inline-rule should win AFAIK.
@domdom, inline has the highest priority
Exactly. What confuses me is that I always thought <style> had a higher priority over <link>, which seems to be backed up at least by this source - has this changed?
If you add styles via link, it goes and sets into the styles after all
Right, the last paragraph on this page seems to confirm it: "Note: If the link to the external style sheet is placed after the internal style sheet in HTML , the external style sheet will override the internal style sheet!" - I learned something today.
0

It takes the style of the stylesheets added latest in your html. Try placing your stylesheet link at the very top.

Comments

0

The code and external links are interpreted sequentially. Which means the bottom most link will override the preceding ones.

Comments

0

This isn't about scope, this is about specificity.

The definition in the file was considered a higher specificity since it was declared later.

There are a lot of other contributing factors to specificity, you can read all about them here: https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.