The <style> tag is used to insert CSS directly into an HTML document. It allows you to define formatting rules without resorting to an external file.
The CSS code is thus placed directly in the <head> tags of the page.
Ideal for quick demos or very localized styles, the <style> tag should however remain the exception: for real projects, favor an external file <link>.
Structure and syntax of the <style> tag
Basic structure and syntax
<style> is a container tag (which works in pairs):
- it has an opening tag:
<style> - as well as a closing tag:
</style>
It must, as we have seen, be placed in the <head> section:
<head>
<style>
selector {
property: value;
}
</style>
</head>
Example
<head>
<style>
body {
font-family: system-ui;
margin: 0;
}
h1 {
color: royalblue;
}
.card {
border: 1px solid #ccc;
padding: 1rem;
}
</style>
</head>Try it yourself:
Attributes
| Attribute | Description | Example |
|---|---|---|
type | MIME type of the content; text/css is implicit in HTML 5. | <style type="text/css"> |
media | Specifies for which media the rules apply (screen, print, etc.). | <style media="print"> |
scoped | Limits CSS to the parent (experimental; not supported by most browsers). | <style scoped> |
Difference with other CSS methods
<style>: Internal CSS – loaded with the page, useful for snippets.<link>: External CSS – better for performance (caching) and maintenance (as it factorizes styles).attribute (inline): only affects a single element, to be reserved for unique cases.
Best practices
Limit <style> to very brief code, prototypes or rare exceptions, but always favor an external stylesheet.
Don't forget that a developer's principle is DRY: Don't Repeat Yourself. So don't duplicate your selectors across multiple pages! 👀
Name your classes in a consistent way (BEM, Utility-First, etc.) to avoid conflicts.
Place the <style> block after the metadata and before the scripts.
Browser compatibility
The <style> tag is supported by all browsers since HTML 2.0; the scoped attribute has little support.
| Browser | <style> tag | scoped attribute |
|---|---|---|
| Chrome | Yes | No |
| Firefox | Yes | No |
| Safari | Yes | No |
| Edge | Yes | No |
| Internet Explorer | Yes | No |