Sub topic 4
Internal Styles: The style Element
An internal stylesheet is a block of CSS written inside a <style> element in the page's <head>. It sits between inline styles, which affect one element, and external stylesheets, which can serve a whole site. This chapter covers how the browser reads that element, what may go inside it, and the errors that cause most "my CSS does nothing" problems.
You should already know the basic HTML skeleton (html, head, body), how to save a text file and open it in a browser, and the parts of a CSS rule (selector, property, value).
A minimal internal stylesheet
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Internal styles</title>
<style>
p {
color: darkblue;
line-height: 1.5;
}
</style>
</head>
<body>
<p>Every paragraph on this page is styled by the style element.</p>
<p>So is this one.</p>
</body>
</html>The text between <style> and </style> is ordinary CSS. The selector p matches every paragraph in this document, so one rule styles both. With a style attribute you would have to repeat the declarations on each paragraph.
How the browser handles the element
<style> is a raw text element. When the HTML parser meets the opening tag, it stops looking for tags and collects everything as plain text until it finds the literal sequence </style>. It then passes that text to the CSS parser. The CSS parser produces a list of rules. The browser matches those rules against the elements in the document.
Two consequences follow from this model:
- Nothing inside
<style>is parsed as HTML. A tag you type there is not an element. It is just invalid CSS text. - Rules apply to the whole document, including elements that appear in the HTML before the
<style>element. Because the stylesheet is processed as part of the head, the page is normally drawn with the styles already known.
Where the element goes
Put <style> inside <head>. The HTML specification allows <style> only where metadata content is allowed (the head), so this is the valid location.
Browsers are forgiving. A <style> element in the <body> still works in practice, and you will see it in older pages and in some generated HTML. It is nonconforming, though, and it has a real cost. The browser may already have drawn some content before it reaches the stylesheet, which can cause a brief flash of unstyled content. A validator will also flag it.
You can have several <style> elements. They are processed in document order, as if their rules were concatenated into one list. This matters for the cascade, covered below.
What goes inside
CSS only
The content must be CSS, with these rules:
- Comments use
/* ... */. HTML comments (<!-- ... -->) are not the right syntax here. Older tutorials wrapped CSS in them to hide it from ancient browsers, which is no longer needed. - Do not write HTML tags inside the element.
- Do not write the sequence
</style>anywhere in the CSS, even inside a string. The HTML parser ends the element at the first occurrence. - Every declaration ends with a semicolon, except that the last one before
}may omit it. Always include it anyway, so adding a declaration later does not break the one before it.
A fuller example
This page uses element, class, and ID selectors, plus a comment:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Recipe card</title>
<style>
/* Page-level defaults */
body {
font-family: system-ui, sans-serif;
max-width: 40rem;
margin: 2rem auto;
}
h1 {
border-bottom: 2px solid #444;
padding-bottom: 0.25rem;
}
.note {
background: #fff6d6;
padding: 0.5rem 1rem;
}
#warning {
color: crimson;
font-weight: bold;
}
</style>
</head>
<body>
<h1>Pancakes</h1>
<p class="note">Rest the batter for ten minutes.</p>
<p class="note" id="warning">The pan is hot.</p>
</body>
</html>The last paragraph gets rules from the .note class and the #warning ID. The ID rule sets color. The class rule does not. The two sets of declarations combine without any conflict.
Attributes on the style element
The <style> element accepts a few attributes you may meet:
| Attribute | Purpose | Example |
|---|---|---|
| `media` | Applies the whole block only when the media query matches | `<style media="print">` |
| `nonce` | Marks the element as allowed under a Content Security Policy | `<style nonce="r4nd0m">` |
| `type` | Legacy. The only useful value is `text/css`, which is the default, so omit it | not needed |
The media attribute is the same idea as on a <link> element. This block applies only when printing:
<style media="print">
nav, footer {
display: none;
}
</style>For most cases you can get the same effect inside a normal block with an @media print { ... } rule. Use whichever keeps your CSS easier to read.
Overlap with other methods
An internal stylesheet takes part in the cascade with the other two methods. Two points are enough for now:
- With equal specificity, the later rule wins. A
<style>element placed after a<link rel="stylesheet">overrides it. If it comes before the link, the linked file overrides it. - A declaration in a
styleattribute beats rules from the<style>element, because it has higher precedence than any selector (unless!importantis involved).
<head>
<link rel="stylesheet" href="site.css">
<style>
p { color: blue; }
</style>
</head>
<body>
<p>Blue, if site.css sets p to another color, because the style element comes later and has equal specificity.</p>
<p style="color: red;">Red, because the inline declaration beats the selector rules above.</p>
</body>Link order is a common source of confusion. If you move the <style> block above the <link>, the first paragraph may change color without any edit to the CSS itself.
Common errors
Most internal-style failures come from a small set of mistakes.
| Symptom | Likely cause | Fix |
|---|---|---|
| Rest of the page disappears | Missing `</style>`, so the parser treats the remaining HTML as CSS text | Add the closing tag |
| Two properties both ignored | Missing semicolon between declarations | End every declaration with `;` |
| Rule has no effect | Selector typo, such as `.Note` against `class="note"` (class names are case-sensitive) | Compare the selector to the markup |
| Rule overridden unexpectedly | A later rule or a more specific selector wins | Inspect the element in developer tools |
| Everything after one rule breaks | Missing or extra brace | Check that each `{` has a `}` |
| Styles blocked in production only | A Content Security Policy forbids inline styles | See the security section below |
Missing semicolon in detail
<style>
p {
color: darkblue
line-height: 1.5;
}
</style>The CSS parser reads darkblue line-height: 1.5 as one value for color. That is not valid, so the browser drops that whole declaration. The paragraph gets neither the color nor the line height. Other rules continue to work, which makes the bug look like a selector problem.
Why nothing is highlighted as an error
Browsers do not report CSS syntax errors on the page. They skip what they cannot parse and carry on. Your editor's syntax highlighting and the developer tools' struck-through or warning-marked declarations are the best early signs.
Reuse and limits
An internal stylesheet is reusable inside one page. One rule can style any number of elements, and you can change a color in a single place. It stops there:
- Another page cannot share it. You must copy the block to each page, and the copies drift apart as soon as you edit one.
- The browser cannot cache it separately. The CSS is part of the HTML document, so it is downloaded again every time the HTML is downloaded.
- Large blocks make the HTML harder to read.
Internal styles do not cost an extra network request, which is their one performance advantage. The browser needs nothing besides the HTML to draw the page.
When it fits
Internal styles work well for:
- A single standalone page, such as a demo, a prototype, or a small personal page.
- A self-contained HTML file that must work without any other files, such as an email template saved locally or a generated report.
- Critical CSS: a small block of above-the-fold rules in the head, with the rest loaded from a file. This is an optimization technique, not a starting point.
- Styles that depend on server-rendered values for that one page.
They fit poorly when more than one page needs the same rules. In that case, move the CSS to an external file.
Security: Content Security Policy
A site can send a Content Security Policy (CSP) response header that limits where styles may come from:
Content-Security-Policy: style-src 'self'This allows stylesheets only from the same origin. Because a <style> element is inline, the browser blocks it unless the policy also permits it. There are two ways to permit it:
'unsafe-inline'allows all inline styles. It is simple, but it removes much of the protection.- A nonce allows specific elements. The server generates a fresh random value for every response, puts it in the header, and adds it to the element:
Content-Security-Policy: style-src 'self' 'nonce-r4nd0m123'<style nonce="r4nd0m123">
p { color: darkblue; }
</style>If styles work on your computer but vanish on a deployed site, open the browser console. A blocked <style> element produces a CSP violation message that names the directive.
Summary of the working model
<style>lives in<head>and contains only CSS.- The HTML parser hands its text to the CSS parser untouched, and ends it at the first
</style>. - Its rules apply to the whole page, in document order alongside linked stylesheets.
- It cannot be shared or cached on its own, and it needs special handling under a strict CSP.
Exercise
A page has a <style> element with p { color: green; }, but no paragraph turns green, and the text after the <style> block is also missing from the page. The closing tag was typed as <style/>. What went wrong, and how do you fix it?
Show answer
<style/> is not a closing tag. The HTML parser treats it as another start tag and keeps collecting raw text, so the rest of the document becomes CSS text that is never displayed. The CSS also fails to apply as intended. Change it to </style>.
Exercise
You have a <link rel="stylesheet" href="site.css"> and a <style> block that both set p { color: ... } with different colors. In which order must they appear in the head for the <style> color to win, and why?
Show answer
The <style> element must come after the <link>. Both selectors have the same specificity, so the later rule in document order wins.
Exercise
Why does a strict Content Security Policy with style-src 'self' stop an internal stylesheet from working, and what is a safer fix than 'unsafe-inline'?
Show answer
A <style> element is inline CSS, not a file from the same origin, so 'self' does not cover it. The safer fix is to add a per-response random nonce to the policy ('nonce-...') and set the same value in the element's nonce attribute. Moving the CSS to an external file also works.