Is adding CSS rules outside the Header possible? [duplicate]
Possible Duplicate:
Declare CSS style outside the “HEAD” element of an “HTML” page ?
I am creating some content that is being used inside a CMS where I do not have access to the header tag. Is there a way to add CSS rules within the <BODY>
of the document?
I want to do this ...
.ClassName
{
border: 2px solid red;
margin: 5px;
padding: 5px;
}
I could add the style rules "inline" inside the element but I wanted to avoid this if possible since the CSS rules will be used in many elements.
I want to avoid this ...
<div style="bor开发者_StackOverflowder: 2px solid red; margin: 5px; padding: 5px">content</div>
You can add <style>
inside body
, but you'll get a validation error:
Element style not allowed as child of element body in this context. (Suppressing further errors from this subtree.)
(This is because it's not allowed according to the specs, see @Oded's answer)
It works just fine in browsers though. Browsers do not care:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<style type="text/css">
.ClassName
{
border: 2px solid red;
margin: 5px;
padding: 5px;
}
</style>
<div class="ClassName">content</div>
</body>
</html>
Yes. You can use a <style>
element.
<style type="text/css" scoped>
.redOutline {
border: 2px solid red;
margin: 5px;
padding: 5px;
}
</style>
<div class="redOutline">content</div>
Answered before :)
But in short, they are invalid but many sites add them to the body, especially those built by (bad) Content Management Systems.
This is not valid HTML, according to the spec.
In the DTD, the STYLE
element appears like this:
<!ENTITY % head.misc "SCRIPT|STYLE|META|LINK|OBJECT" -- repeatable head elements -->
Where the head.misc
only appears as pard of HEAD
or TITLE
.
However, as others have noted, many browsers will still parse and use stylesheets that have been defined within the body tags. Your mileage may vary... in particular if you do use a DOCTYPE in your markup.
精彩评论