The <style>
tag in HTML is used to define internal CSS styles directly within an HTML document. This allows you to control the look and feel of your web page without needing an external stylesheet file.
📌 What Is the <style>
Tag?
- The
<style>
element contains CSS code that applies styles to elements on the page. - It is placed inside the
<head>
section of an HTML document. - Styles defined inside
<style>
affect the entire document or specified selectors.
✅ Basic Syntax
<head>
<style>
body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}
h1 {
color: navy;
}
</style>
</head>
🧪 Example 1: Styling Paragraphs and Headings
<head>
<style>
p {
color: #333;
font-size: 16px;
line-height: 1.5;
}
h2 {
color: darkgreen;
}
</style>
</head>
<body>
<h2>Welcome to My Website</h2>
<p>This is a styled paragraph using the <style> tag.</p>
</body>
🎨 Features
Feature | Description |
---|---|
CSS inside HTML | Embed styles directly within HTML |
Scope | Styles affect the whole document unless scoped |
Overrides external CSS | Styles here can override linked stylesheets if placed after them |
⚠️ Best Practices
- Use
<style>
for small or page-specific CSS. - For larger projects, use external CSS files linked via
<link>
for better maintainability. - Avoid placing large CSS inside
<style>
in the body (HTML5 allows it but is discouraged). - Always put
<style>
inside the<head>
for best practice.
🧩 Example 2: Scoped Styles (HTML5 feature)
<section>
<style scoped>
p {
color: blue;
}
</style>
<p>This paragraph is blue only inside this section.</p>
</section>
<p>This paragraph is default color.</p>
Note: The scoped
attribute is not widely supported and generally not recommended for production use.
🔁 <style>
vs External CSS
Method | Pros | Cons |
---|---|---|
<style> tag | Quick, inline styling, good for demos | Not reusable, harder to maintain |
External CSS file | Reusable, caches in browser, maintainable | Requires extra HTTP request |
🏁 Summary
The <style>
tag is a powerful way to include CSS rules directly inside your HTML documents. It’s great for small-scale styling or quick prototypes but less ideal for large websites where external CSS files shine.