Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having stylesheet <link> in <body>?

Tags:

html

css

xhtml

Is it a bad idea to link CSS files inside the body?

I've read that the browser is forced to start CSS rendering over again if it finds another CSS file outside of head, just because it might need to apply styles to elements it's already rendered. Also I don't think the HTML will validate properly (I need to confirm this).

Are there any other reasons?

like image 585
mawaldne Avatar asked Dec 03 '09 19:12

mawaldne


Video Answer


2 Answers

The questions have been answered (is it bad, why...) but the correct way to achive that if you can't add your links (or scripts) in the header, is to dynamically insert them with javascript. It's also sometime a good idea for improving the speed of your code. For the links you can use this function:

function loadCss(url) {
    var link = document.createElement("link");
    link.type = "text/css";
    link.rel = "stylesheet";
    link.href = url;
    document.getElementsByTagName("head")[0].appendChild(link);
}

You should use a JavaScript file loader like require.js for the scripts.

like image 113
Pierre Avatar answered Oct 09 '22 13:10

Pierre


The only reason I've seen people use to justify doing this is when they're using certain templating engines, and they can't arbitrarily change the stylesheets linked in the head when loading new content or a particular view (in the case of MVC frameworks).

Either way, this should be avoided at all costs as it's sloppy, and improper. Instead, always develop your projects in such a way that you can get an arbitrary stylesheet into the head at any time. I generally do this by cycling through a stylesheet array in the head. That way, if I need to add a new stylesheet, I simply add its pathname to the array to be printed in the head.

<?php

  $styles   = array();
  $styles[] = "css/main.css";
  $styles[] = "css/text.css";

?>

<head>
  <?php foreach ($styles as $style) { ?>
    <link href="<?php print $style; ?>" rel="stylesheet" type="text/css" />
  <?php } ?>
</head>
like image 40
Sampson Avatar answered Oct 09 '22 15:10

Sampson