ajmajmajma ajmajmajma - 2 months ago 8
CSS Question

CSS override, first loaded style sheet taking precedent

I have a very strange issue I cannot quite figure out with my css style sheets. I have 2 stylesheets, one is from a cdn, one is minified then injected onto my index.html (locally) on my local dev server right now. So just for a quick reference, in my header I have something like this :

<link rel="stylesheet" href="myCDNStyleSheet.css">
<!-- injector:css -->
<link rel="stylesheet" href="css/localMinifiedStyles.css?1474574347809">
<!-- endinjector -->


So that is just using a grunt task with
grunt-cssmin
and
grunt-injector
to put that stylesheet with it's own hash on.

Now what's weird is, even though the
myCDNStyleSheet
is loaded first, some styles from it are taking precent over styles in the
localMinifiedStyles
, and so currently, I've had to put some
!important
on the styles in 'localMinifiedStyles', which is very strange to me.

So to be super clear, what I mean is :

myCDNStyleSheet.css
has :

.styleMe {
margin-left: 5px
}


and
localMinifiedStyles.css
has :

.styleThis {
margin-left: 12px
}


And the rendered html looking like :

<div class="styleMe styleThis">


is using the
margin-left: 5px
instead of the 12. I can see them both in the inspector.

Swapping their load order does not fix this, in fact it breaks it further because there are some styles in
localMinifiedStyles
that are taking priority correctly.

Even when inspecting the styles in chrome devtools, I see the
localMinifiedStyles
is below the style that is taking precent. I can't figure out the cause of this, is it possible the grunt injection does something I am not aware of? My assumption thus far in working with css is the last loaded stylesheet takes priority, and I missing something here?

Answer

I'm really not sure what caused the behavior you describe (If you have the exact same "priority" of css rule - the latter will win), however a simple way to fix your problem is to duplicate the class in your css definition. If you want the styleThis class to take over you can use:

.styleThis.styleThis {
    margin-left: 12px;
}

It's kind of a hack, but it works in up to date versions of chrome, firefox and ie.

.green.green {
  color: green;
}
.red {
  color: red;
}
<div class="red green">
  This text's color should have been red because the red rule is latter in the CSS, however it will be green due to the <code>.green.green</code> in the css rules.
</div>

Comments