mawaldne mawaldne - 1 year ago 53
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?


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

Answer Source

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.


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


  <?php foreach ($styles as $style) { ?>
    <link href="<?php print $style; ?>" rel="stylesheet" type="text/css" />
  <?php } ?>