Using two css files in the same html file
Asked Answered
C

5

9

Is it possible to use 2 CSS classes that have the same name for the selectors, etc. in the same HTML file? If so, how do you differentiate between the two when styling elements?

Christelchristen answered 16/12, 2008 at 20:48 Comment(0)
B
24

Yes this is possible, simply include two css files in the HEAD section of the document. Any styles set in the first will be overwritten in the second, so say you have this:
First file:

 #something{
  background-color: #F00;
  color: #FFF;
 }

And then in the second file:

 #something{
  background-color: #000;
 }

Then the background color for #something will be overwritten in the second file to black but the color will stay the same since the second file doesn't say anything about it.

Bram answered 16/12, 2008 at 20:52 Comment(1)
Keep in mind this only happens at the same specificity - if the earlier one was #something .blah then that would win out.Isoleucine
E
2

Yes it is possible. The definitions in second file will overwrite the definitions of the first file. There is no way to differentiate between the two but to prepend the class names according to the file.

Emmalineemmalyn answered 16/12, 2008 at 20:49 Comment(0)
S
2

This should work, try it.

<style>
  .foo{
    border:1px solid blue;
    color:red;
  }
  .foo{
    border:4px solid orange !important;
  }
</style>
<div class="foo">this will have an orange border and red text (no blue border)</div>
Selfevident answered 16/9, 2011 at 12:27 Comment(0)
S
1

...that have similar names for the selectors

If the names really are similar and not identical then there shouldn't be a problem.

Stablish answered 16/12, 2008 at 20:50 Comment(1)
Well, then the overwrite answers that you already have are the right answer.Stablish
P
0

do you mean 2 definitions for the same class? or 2 class names on an element?

The first case, no.

<style>
  .foo{
    border:1px solid blue;
    color:red;
  }
  .foo{
    border:4px solid orange;
  }
</style>
<div class="foo">this will have an orange border and red text (no blue border)</div>

The second case, yes

<div class="class1 class2">this is valid</div>
Piper answered 16/12, 2008 at 20:49 Comment(3)
2 similar class names in 2 separate files.Christelchristen
Well, true. But, misleading. Each new definition expands/overrides the last. The "foo" div will still have red text.Pity
Ah my bad, my code sample didn't match my thought. Xaisoft: if the names are different, then you are totally fine, you can do whatever you want. The only issue is if the names are the exact same.Piper

© 2022 - 2024 — McMap. All rights reserved.