I am stuck in a situation where I only have access to the body of the website and not the head. I have to use a new stylesheet. Now the solution that I came across to add the CSS file in the body of the website. Of course, it is a hack so I was wondering if there is a better solution to it?
-
you could add with javascript your stylesheet to the head during runtime. – Sven Bieder Aug 06 '12 at 17:51
-
see this http://stackoverflow.com/questions/2685614/load-external-css-file-like-scripts-in-jquery-which-is-compatible-in-ie-also – voodoo417 Aug 06 '12 at 17:53
-
@SvenBieder: I am little new with javascript so I want to stick the solution in html/css only. Still, thanks for the solution. – Aug 06 '12 at 17:58
-
@voodoo417: That would work, provided that the head includes jQuery. – Aug 06 '12 at 18:04
-
`.innerHTML += "";` should work for just javascript. – Kwon Aug 06 '12 at 18:22
-
Why do you think it's a hack? Stylesheet links are [`body-ok`](https://html.spec.whatwg.org/multipage/links.html#body-ok) which means they are allowed in the `` section of a page. Using javascript to insert the link in the `` as many of the current solutions recommend seems much worse. What happens if someone has javascript disabled? Some adblockers and aggressive anti-virus might block it. (maybe this question is showing it's age) – AnnanFay Jun 09 '19 at 01:57
6 Answers
We have different ways to load a CSS File.
1 - HTML - The conventional way to load external CSS files on a page is:
<head>
<link rel="stylesheet" type="text/css" href="file.css" />
</head>
2 - CSS - Using the tag import
from your CSS file
@import url("another_file.css");
3 - JavaScript - Using only JavaScript to do it, you should create a Javascript function:
<script type="text/javascript">
function loadCSS(filename){
var file = document.createElement("link");
file.setAttribute("rel", "stylesheet");
file.setAttribute("type", "text/css");
file.setAttribute("href", filename);
document.head.appendChild(file);
}
//just call a function to load your CSS
//this path should be relative your HTML location
loadCSS("path_to_css/file.css");
</script>
4 - JavaScript - Either you can add dynamic definitions such as:
<script type="text/javascript">
var sheet = (function() {
var style = document.createElement("style");
style.appendChild(document.createTextNode(""));
document.head.appendChild(style);
return style.sheet;
})();
sheet.insertRule("span { visibility: hidden }", 1);
</script>

- 1,090
- 11
- 16
-
4Or you can use `document.head` instead of `document.getElementsByTagName("head")[0]`. – Timothy Gu Apr 08 '15 at 14:42
-
1In what circumstances you can get `file` to be undefined here? You just created it. – vittore Jun 21 '16 at 13:09
-
@vittore you are right, the code described at HTML5Rocks show that is not necessary http://www.html5rocks.com/en/tutorials/speed/script-loading/ Futhermore, I found at Mozilla reference from createElement that it won't return undefined https://developer.mozilla.org/pt-BR/docs/Web/API/Document/createElement – well Jul 29 '16 at 11:12
what about:
$('head').append('<link rel="stylesheet" type="text/css" href="{yoururl}">');

- 2,367
- 3
- 30
- 53
-
-
This jquery hack wont work unless it is called from within the head. the css file wont be parsed otherwise. At least thats my experience. – DeveloperChris Jul 19 '18 at 06:43
-
Javascript is best practice to run after all your other html? shouldn't matter, i do lacy load of css so i only show critical before - same solution to different problems – Simon Dragsbæk Jul 19 '18 at 07:36
Do you mean define CSS again and override previous CSS like?:
<html>
<head>
<style type='text/css'>
* {color:red;}
p {background-color:yellow;}
</style>
</head>
<body>
<style type='text/css'>
* {color:green;}
p {background-color:black;}
</style>
<p>"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..." </p>
"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."
<p>"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..." </p>
</body>
</html>
You could copy the entire style sheet there or of course then include it with php or javascript.But like this, looking at the head CSS stylesheet and overriding all the styles appearing there in the body should work. Not sure if this is clean though.

- 2,399
- 2
- 22
- 29
-
-
1I checked this HTML in https://validator.w3.org/. It states `Error: Element style not allowed as child of element body in this context. (Suppressing further errors from this subtree.)` I think @Bachsau's comment is correct, though based on other answers it sounds like many (maybe most? maybe all?) browser support this non-standard form. But it's not clear if it would break some browsers now or perhaps in the future. – David Parks Oct 06 '20 at 16:45
-
@DavidParks Browsers support a lot of non standards things and always did. But people should follow the standards or otherwise, we will end up with the same situation we already were in some years ago, where a website looks different in every browser and creators start to optimize for a single browser, locking everyone else out. – Bachsau Oct 06 '20 at 16:59
-
well, its not a great solution but is an option you have as the title clear states CSS hack and even not valid, will work where valid standard html wont, for example appending the style to the head with javascript if the user-agent has disabled js (I dont know the context where this hack was needed). I tend to think not everyone is an erudite and only codes the best code ever, sometimes you need a solution that works, that solves a problem a quick hack and go on, like 'this', the context is everything and people should not have any should more than their own real should – Santiago Rebella Nov 27 '20 at 02:49
You could use the @import url("your_styles.css");
method.
If you have access to the stylesheets being called in the head of the document, you can add this at the top of the CSS doc.
You could try adding an alternate <head>
to your doc as well, which I do not advise, but if you have to then you can also do this:
<style type="text/css">
@import url("your_style.css");
</style>
If backwards compatibility is not a concern for you, there is also the HTML5 scoped
attribute which has been addressed in this question: Does <STYLE> have to be in the <HEAD> of an HTML document?
Hope this helps!
EDIT:
Found two links in regards to @import feature. One is a working draft from Mozilla Developers center which was last updated on Jul 31, 2012:
https://developer.mozilla.org/en-US/docs/CSS/@import
Also a Sitepoint Reference article with browser support stats:
http://reference.sitepoint.com/css/at-import
I would imagine this is still a functional, usable feature when necessary.
-
@StartupCrazy as far as I know it is still valid code. Something I would use in a pinch, if necessary. – robabby Aug 06 '12 at 18:17
-
1Thats what I was told when I researched about it, http://stackoverflow.com/questions/9884182/why-dont-we-import-css-in-a-div – Aug 06 '12 at 18:20
-
1
Apperently, it seems to work for me, if it looks like
<link href="/main.css" rel="stylesheet" type="text/css" />
but not, if it contains the /css
in rel.
<link href="/main.css" rel="stylesheet/css" type="text/css" />
Just tested this myself, thought about posting this to underline this pitfall.

- 3,221
- 35
- 38
-
2Stylesheet links are [`body-ok`](https://html.spec.whatwg.org/multipage/links.html#body-ok) which means they are allowed in the `` section of a page. Is `stylesheet/css` even a valid value for `rel`? From what I can tell you *can* have multiple values but they must be space separated. – AnnanFay Jun 09 '19 at 02:03
-
@BananaAcid, your **rel="stylesheet/css"** is invalid, which is why it doesn't work. See valid values at https://www.w3.org/TR/html52/links.html#linkTypes – McAuley Jan 01 '21 at 19:46
You can place <head></head>
tags in your body section.

- 400
- 3
- 12
-
+1 Good one. Is it any better than placing the links directly inside the body? – Aug 06 '12 at 19:08
-
-
Here is my real widget:http://widgetsinabottle.com/saad_widget/effect.html Here is the one I created using your advice: http://widgetsinabottle.com/home – Aug 06 '12 at 19:18
-
Make sure the css is enclosed in `` tags if you hadn't. It seems jQuery is valid, though. – Kwon Aug 06 '12 at 19:31
-
I have enclosed the css and javascript into the `` tag. However, the images do not load still. – Aug 06 '12 at 19:56
-
3
-
1