✅ Three Main Ways to Use CSS in a Project
-
Inline CSS
Styles are applied directly to individual HTML elements using the
style
attribute. Use case: Quick, one-off styling or dynamic styling via JavaScript. Example:
<p style="color: red;">This is red text.</p>
-
Internal CSS
Styles are written inside a
<style>
tag within the HTML<head>
. Use case: Single-page applications or prototypes where styles don’t need to be reused. Example:
<head>
<style>
body {
background-color: lightgray;
}
</style>
</head>
-
External CSS
Styles are stored in a separate
.css
file and linked using a<link>
tag. Use case: Larger, multi-page websites or apps that need consistent, reusable styling. Example:
<head>
<link rel="stylesheet" href="styles.css" />
</head>
🎯 CSS Specificity (How Conflicts Are Resolved)
CSS specificity determines which rules apply when multiple rules target the same element. Think of it as a weight system or score for selectors:
Specificity hierarchy (from highest to lowest):
Selector Type | Example | Weight |
---|---|---|
Inline styles | style="..." |
1000 |
IDs | #header |
100 |
Classes, pseudo-classes |
.menu , :hover
|
10 |
Elements/pseudo-elements |
div , p , ::before
|
1 |
-
Example:
Given both
.menu
and#header
target the same element,#header
wins due to higher specificity.
Tie-breaker: Source order
If two rules have equal specificity, the one that appears later in the stylesheet wins.
The nuclear option: !important
- Overrides all specificity rules.
- Use sparingly – it makes debugging harder and can create maintenance headaches.
.button {
color: blue !important;
}
🧠 Developer Tip
Understanding specificity helps you avoid confusing bugs where styles don't apply as expected.
Use developer tools (like Chrome DevTools) to inspect computed styles and see which rules are being applied and overridden.
Top comments (0)