mawaldne mawaldne - 4 months ago 8
CSS Question

Having <link> in <body>?

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 its already rendered. Also I don't think the html will validate properly (I need to confirm this).

Are there any other reasons?

Edit:

Sorry, I should of said having < link> inside of body. I corrected the question.

Answer

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>