CSS (Cascading Style Sheets) code can be written in a few different places, each with its own advantages and disadvantages. Primarily, CSS can be written inline, internally, or externally.
Methods of Coding CSS
Here's a breakdown of the common methods for implementing CSS:
-
Inline CSS:
- Written directly within HTML tags using the
style
attribute. - Affects only the specific element where the style is applied (and potentially its child elements, depending on the CSS properties used).
- Example:
<p style="color: blue;">This is a blue paragraph.</p>
- Best use: Quick, element-specific styling, or testing.
- Written directly within HTML tags using the
-
Internal CSS:
-
Placed inside a
<style>
element within the<head>
section of the HTML document. -
Applies styles to all matching elements within that specific HTML page.
-
Example:
<!DOCTYPE html> <html> <head> <style> p { color: blue; } </style> </head> <body> <p>This is a blue paragraph.</p> </body> </html>
-
Best use: Single-page websites or when specific styles are unique to one page.
-
-
External CSS:
- Written in a separate
.css
file. - Linked to HTML documents using the
<link>
tag in the<head>
. - Example:
<link rel="stylesheet" href="style.css">
- Best use: Large websites, consistent styling across multiple pages, easier maintenance.
- Written in a separate
Choosing the Right Method
The best place to write your CSS depends on the scope and complexity of your project.
Method | Location | Scope | Advantages | Disadvantages | Use Case |
---|---|---|---|---|---|
Inline | Inside HTML tag using the style attribute. |
Specific HTML element. | Quick styling of a single element. | Difficult to maintain, not reusable. | Small, element-specific changes. |
Internal | Within <style> tag in HTML's <head> . |
All matching elements on a single HTML page. | Easy to implement, good for single-page sites. | Not reusable across multiple pages. | Single-page websites, unique page styling. |
External | Separate .css file. |
Multiple HTML pages. | Reusable, easy to maintain, best for large projects. | Requires an extra file, may increase load time. | Large websites, consistent styling across pages. |