Skip to main content

The HTML Style Element

CSS is how you make a page look good. Most of the time, you keep CSS in a separate file and connect it with a <link>. But sometimes you want the CSS to travel inside the page itself. For that, HTML has the <style> element.

It is a small element with a few important details: where it goes, how it competes with other styles, and how modern security rules treat it. In this lesson you will learn all three.


What You Will Learn​

  • What <style> is, and what goes inside it
  • Three ways to add CSS: <link>, <style>, and the style attribute
  • When an internal style block is a good idea, and when it is not
  • How the order of rules and specificity decide who wins
  • Using media and nonce on <style>
  • How a Content-Security-Policy can block inline styles
  • Adding styles with JavaScript

The Big Idea​

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Styled in the page</title>
<style>
body { font-family: sans-serif; padding: 12px; }
.card { border: 2px solid #1d4ed8; border-radius: 10px; padding: 12px; background: #eff6ff; }
h2 { margin: 0 0 6px; color: #1d4ed8; }
</style>
</head>
<body>
<div class="card">
<h2>Fresh Bread</h2>
<p>Baked every morning.</p>
</div>
</body>
</html>

Change the CSS and watch the page. Try the presets, or write your own rules.

What Is Inside <style>?​

Everything between <style> and </style> is read as CSS, not HTML. That means:

  • You write normal CSS rules: selectors and declarations.
  • You do not write HTML tags inside it.
  • You do not need to escape characters such as > or &. Child selectors such as ul > li work as written.
  • The only thing that ends it is the text </style>.
<style>
/* This is a CSS comment, not an HTML comment */
nav > a { color: navy; }
a[href^="https"]::after { content: " β†—"; }
</style>

Three Ways to Add CSS​

WayExampleGood forNot good for
External file with <link><link rel="stylesheet" href="site.css">Most real sites: shared by every page, cached by the browserPages that must work as one single file
Internal block with <style><style>h1 { color: navy; }</style>Small pages, demos, per-page rules, critical CSSBig shared styles repeated on every page
Inline attribute with style<p style="color: red">One-off values set by script, or quick testsAnything you will maintain. It is the hardest to override

When <style> Is the Right Choice​

  1. A single-file page, such as a demo, an email template (with some limits), or a small tool.
  2. Rules that belong to one page only, which no other page needs.
  3. Critical CSS: the few rules needed to draw the top of the page, placed inline so the first display does not wait for a file. The rest loads from a <link>.
  4. Learning and experiments, because everything is in one place.

When to Choose a File Instead​

  • The same rules are used on many pages. A file is downloaded once, then cached. An inline block is downloaded again with every page.
  • Many people edit the CSS. One file is easier to find and review.
  • Your security policy forbids inline styles (see below).
A good default

Use an external file for your main styles. Use a small <style> block only for critical CSS or rules unique to a page.

Where to Put It​

Put <style> in the <head>, not in the body.

<head>
<link rel="stylesheet" href="/css/site.css">
<style>
/* Page-specific rules, after the shared file */
</style>
</head>

A <style> in the body works in browsers, but it is not valid HTML in that position, and the page may flash unstyled while the browser reads down to it. Keep it in the head, near the other styles.

Who Wins? Order and Specificity​

Several rules can target the same element. The browser decides in this order:

  1. Importance: !important rules beat normal ones.
  2. Specificity: a more specific selector wins. An id beats a class, and a class beats an element name.
  3. Order: if importance and specificity are equal, the later rule wins.

This is the cascade, the "C" in CSS. Style blocks and linked files all take part, in the order they appear in the page. Try it:

cascade.html
<style>
h2 { color: crimson; } /* block A */
</style>
<style>
h2 { color: seagreen; } /* block B, later, so it wins */
</style>

Advice that keeps your CSS calm:

  • Avoid !important. It is a last resort, and leads to more !important.
  • Prefer classes over ids and over very long selectors.
  • Put page-specific <style> after shared <link> files, so it can override them when needed.
  • Modern CSS also has cascade layers (@layer) for organising which group of rules wins. You will meet them in the CSS lessons.

Attributes of <style>​

AttributeUse
mediaApply the whole block only when a condition is true, such as media="print"
nonceA one-time value that lets a strict security policy allow this block (see below)
blockingAdvanced: control whether the block holds back rendering
typeNot needed. CSS is the default. Old pages wrote type="text/css"
titleRarely used, for alternate stylesheets
<style media="print">
nav, footer, .ads { display: none; }
body { font-size: 12pt; color: #000; background: #fff; }
</style>

Styles and Security: Content-Security-Policy​

A Content-Security-Policy (CSP) is a set of rules, usually sent by the server, that says what a page may load and run. Its style-src rule controls CSS.

A strict policy such as style-src 'self' blocks all inline styles: both <style> blocks and style attributes, unless you give them permission. That protects against some attacks, but it means your inline CSS stops working.

Ways to allow inline CSS safely:

MethodHow it worksNotes
NonceThe policy names a random value ('nonce-abc123'). Only <style nonce="abc123"> blocks runThe value must be new and unguessable on every response
HashThe policy lists a fingerprint of the exact CSS textAny change to the text needs a new hash
'unsafe-inline'Allows all inline stylesSimple, but weakens the protection
External fileAllow your own origin with 'self'Often the simplest answer

Experiment below. A small page has two paragraphs: one styled by a <style> block, one by a style attribute. See which rules each policy lets through.

csp-style.html
<meta http-equiv="Content-Security-Policy" content="style-src 'nonce-abc123'">

<!-- Allowed: the nonce matches -->
<style nonce="abc123">
#a { color: green; }
</style>

<!-- Blocked: a nonce does not cover style attributes -->
<p style="color: red">Hello</p>

You can see a good lesson in the results: a nonce can allow a <style> block, but the inline attribute stays blocked. That is why many sites move one-off styles into classes.

Adding Styles with JavaScript​

Sometimes styles come from script. A few options, from simplest to most modern:

// 1. Change one element's inline style (blocked by a strict policy)
element.style.color = "crimson";

// 2. Toggle a class, and keep the CSS in your stylesheet (usually best)
element.classList.add("is-active");

// 3. Set a CSS variable, and let your stylesheet use it
document.documentElement.style.setProperty("--brand", "#1d4ed8");

// 4. Create a constructable stylesheet (works with strict policies)
const sheet = new CSSStyleSheet();
sheet.replaceSync("h2 { color: seagreen; }");
document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];

Toggling a class is usually the cleanest choice, because the CSS stays in one place, and it works with strict security policies. Support for constructable stylesheets is good in modern browsers, but check the browsers you need.

Styles in Docusaurus​

In this documentation site, you normally style with src/css/custom.css and CSS modules, and write style={{}} objects in React components, like the demos on these pages. Those become real styles in the built site. If you need a raw <style> block in a page, put it inside @docusaurus/Head or use a component, since MDX handles curly braces in its own way.

Good Habits​

  1. Keep the main CSS in an external file.
  2. Use <style> for critical or page-only rules.
  3. Put it in the head, after shared stylesheets.
  4. Prefer classes to inline style attributes.
  5. Avoid !important.
  6. Keep inline blocks small, because they are re-downloaded with every page.
  7. Use media for print and other special cases.
  8. Plan for a strict CSP, with nonces or an external file.
  9. Never put untrusted text inside a style element.

Accessibility Checklist​

  • Your styles never remove focus outlines without a clear replacement.
  • Text contrast meets the guidelines (at least 4.5 to 1 for normal text).
  • The page still works if the user overrides colours or fonts (high-contrast mode, custom styles).
  • Sizes use relative units (rem, em), so text zooms properly.
  • prefers-reduced-motion is respected for animations.
  • A print stylesheet keeps text readable on paper.
  • display: none and visibility: hidden are not used to hide content that should stay available to screen readers.

Security and Privacy Notes​

  • Never put user-supplied text inside <style>. A visitor who can add </style><script>… can break out. Even without scripts, CSS can be used to hide or rearrange parts of a page, or, in some attacks, to leak data.
  • A strict CSP blocks inline styles for a reason. Use nonces, hashes, or an external file instead of 'unsafe-inline'.
  • Nonces must be random, secret until the response, and different every time. A fixed or guessable nonce gives no protection.
  • Do not let inline CSS load private resources (a url() that includes a token or personal data), because the request goes in plain sight in network logs.
  • CSS can fetch files (url(), @import, fonts) from other sites, which reveals visits. Host files yourself when privacy matters.
  • Comments in CSS are public. Remove notes about internal tools or unreleased features.

Global Audience Notes​

  • Use logical properties (margin-inline-start, padding-block) so layouts work in both left-to-right and right-to-left languages.
  • Choose font stacks that cover your audience's scripts, and test long words and translations.
  • Do not set fixed widths on text boxes. Translated text can be 30 percent longer.
  • Keep inline CSS small: every byte is downloaded again on each page, which matters on slow or expensive connections.
  • Respect prefers-color-scheme, prefers-reduced-motion, and prefers-contrast. They are personal settings, and apply everywhere.
  • Print and paper sizes differ (A4 and Letter), so test your print styles with both.

Common Mistakes to Avoid​

  1. Putting HTML tags inside <style>.
  2. Putting <style> in the body.
  3. Repeating a big stylesheet in every page.
  4. Using !important to win arguments between rules.
  5. Forgetting that order matters between blocks and linked files.
  6. Relying on inline style attributes everywhere.
  7. Breaking a strict CSP with inline styles, and not knowing why.
  8. A fixed or reused nonce.
  9. Putting untrusted text in a style element.
  10. Leaving type="text/css" everywhere (it does no harm, but is not needed).
  11. Removing focus outlines.
  12. Not testing print styles.

Practice Time​

Try these in your editor:

  1. Add a <style> block with three rules to a plain page.
  2. Move the rules to an external file, and link it. Compare the result.
  3. Write two conflicting rules, and swap their order to see who wins.
  4. Make a class rule beat an element rule, then try !important, and then remove it.
  5. Add a media="print" style block, and use print preview.
  6. Replace one inline style attribute with a class.
  7. Add a Content-Security-Policy meta tag, and see which of your styles stop working.
  8. Fix them with a nonce, then try moving them to a file.
  9. Create a constructable stylesheet with JavaScript.
  10. Bonus: split a page's CSS into critical (inline) and the rest (linked), and measure the difference in developer tools.

Quick Recap​

Click a question to check your answer.

1. What goes inside a style element?

CSS rules, and nothing else. The browser reads everything up to the closing </style> as CSS, not HTML.

2. When is style better than a linked file?

For single-file pages, critical CSS, and rules that belong to just one page. For shared styles across many pages, a cached external file is better.

3. If two rules have the same importance and specificity, which wins?

The one that appears later in the page.

4. Where should style go?

In the head, after any linked shared stylesheets.

5. What does a strict style-src policy do to inline CSS?

It blocks both style blocks and style attributes, unless you allow them with a nonce, a hash, or 'unsafe-inline'. A nonce covers blocks, not attributes.

6. Why is toggling a class often better than setting element.style?

The CSS stays in your stylesheet, it is easier to maintain, and it works with strict security policies.

Key Takeaways​

  • <style> holds CSS inside the page. Put it in the head.
  • Use external files for shared styles, and <style> for critical or page-only rules.
  • The cascade decides: importance, then specificity, then order.
  • A strict Content-Security-Policy blocks inline styles. Use nonces, hashes, or files.
  • Avoid !important and many inline style attributes.
  • Never place untrusted text inside a style element.
  • Keep styles accessible: contrast, focus outlines, relative units, and respect for user preferences.

Next, add behaviour to your page with the Script element.