What is the best way to include a style sheet for a specific page?
thank you for viewing.
My website includes the same header and footer for each page using PHP.
I wanted a style sheet that only applied specifically for a certain page, so put the style in using the appropriate tag.
...<body><style type="text/css"> /* what ever */ </style></body>...
The style sheet is processed correctly in all browsers I tested, however it is not validated correctly by W3C because it's located inside the body tag instead of the head.
My question is:
If I can't put the style sheet in the body tag, what is the best way to include it? I can reference the style sheet in the PHP header, but I'd rather not have another HTTP Request for such a small file. How would you do it? What is the least sloppy way to do it? Although 开发者_开发问答the style tag shouldn't be in <body>, it is still processed correctly by browsers.What about giving the body an id and then just including the page specific files in the general CSS but with the styles prefixed by the id selector? Something like this:
On page
<body id="pageSpecificId">......</body>
In CSS file:
#pageSpecificId p {
... paragraph specific styles ...
}
#pageSpecificId li {
... list item specific styles ...
}
The best way would be to use a MVC framework that buffers your view file, and allow tag to be dynamically added to the head before output.
Here is a ultra simple way of doing it:
index.php:
<?php
class Page {
private static $head = array();
private static $content = '';
static function add_head($tag) {
self::$head[] = $tag;
}
static function render_head() {
foreach (self::$head as $tag) echo $tag;
}
static function render_content() {
echo self::$content;
}
static function read_content($file) {
ob_start();
require $file;
self::$content = ob_get_clean();
}
static function render_layout($file) {
require $file;
}
}
Page::read_content('view.php');
Page::render_layout('layout.php');
?>
layout.php:
<html>
<head><?php Page::render_head(); ?></head>
<body>
<div id="header"></div>
<div id="content"><?php Page::render_content(); ?></div>
<div id="footer"></div>
</body>
</html>
view.php:
<?php Page::add_head('<title>Hello World!</title>'); ?>
<h1>Hello</h1>
<p>World</p>
精彩评论