1

Is it possible to make an external stylesheet override all conflicting styles? The use case for this is appending a link to a stylesheet that changes the colors of a page to different colors. I have tried appending the stylesheet to the tag using javascript but I found that other stylesheets colors interfered with mine.

var link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = `https://randomwebsite.com/main.css`
document.head.appendChild(link);

Edit: I found out why this was happening. The issue was that the tag was appending the beginning of the head when I wanted to append it to the end. Thank you to all that helped me.

  • Cascade layers might be what you want. If you posted a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) we'd be able to tell. – Alohci Dec 29 '22 at 02:31
  • Please could you describe what 'interfered with' actually means? When you go into your browser's devtools inspect facility are you finding that the CSS is being overridden by, for example, an !important coming from a previous stylesheet? – A Haworth Dec 29 '22 at 08:50
  • @AHaworth I am finding that the css is being overridden by the last stylesheet in the tag. My problem is that when I append my stylesheet to the head it is appending to the beginning of the head, not the end. – Potter Edgerton Dec 29 '22 at 16:35
  • That's probably the real question you should be asking then. Because `document.head.appendChild(link)` will append to the end of head, as it is at the time that the script runs. So you question should be, why is it apparently appending to the beginning? Without the full context of your script we can't tell that, hence why we ask for a minimal reproducible example. However, the most common explanation is that it's running too soon. Consider putting it in a block that only runs when the window load event fires. – Alohci Dec 29 '22 at 17:35
  • It's appending to the head as it is at the time you are doing the appending. If it's at the start of the head that means other things have not yet got in there. Please try to create a snippet of code which includes your code and an example of one of the other links. – A Haworth Dec 29 '22 at 18:05
  • @AHaworth I fixed the issue. I was using element.appendChild(element) instead of element.append(element) – Potter Edgerton Dec 29 '22 at 18:08

1 Answers1

1

CSS rules are sequential, in your header tags the last stylesheet will always go first!

check this post : Can one CSS file take priority over another CSS file?

Mehdi
  • 385
  • 1
  • 12