Sub topic 2
Internal, External, and Overlapping CSS Styles
Assume you know basic HTML, can edit files, and understand relative file paths. This chapter focuses on choosing where CSS lives and predicting which declaration wins.
Internal styles: the `style` element
An internal stylesheet is a <style> element inside the document’s <head>. Its CSS applies only to that HTML document.
<head>
<meta charset="utf-8">
<title>Internal styles</title>
<style>
p {
color: darkblue;
line-height: 1.5;
}
</style>
</head>The selector p matches every paragraph on the page. Internal styles are useful for page-specific rules or prototypes, but they must be repeated when several pages need the same design.
External styles: linking a stylesheet
An external stylesheet is a separate .css file. Link it from the <head> with rel="stylesheet" and a path in href.
<link rel="stylesheet" href="css/site.css">The linked file contains CSS only:
/* css/site.css */
body {
font-family: system-ui, sans-serif;
margin: 2rem;
}
p {
color: darkgreen;
}External CSS supports reuse, easier maintenance, browser caching, and stronger Content Security Policy settings. The path is resolved relative to the HTML document, so an incorrect path prevents the stylesheet from loading.
When methods overlap: cascade and source order
When multiple declarations match an element, the CSS cascade chooses a winner. For declarations with equal specificity, the later declaration wins.
<link rel="stylesheet" href="site.css">
<style>
p { color: blue; }
</style>Here, the internal rule follows the external rule, so it wins if both selectors are simply p. A later rule in the same stylesheet can also override an earlier rule.
>callout note The cascade considers more than source order. Importance, cascade layers, origin, specificity, and source order all affect the result. </callout>
Specificity and inline style precedence
Specificity is the selector’s priority. An ID selector is more specific than a class selector, which is more specific than an element selector. A normal inline declaration usually beats declarations from these selectors:
<p class="notice" style="color: red;">This text is red.</p>The inline declaration wins over p { color: blue; } and .notice { color: green; }. An !important declaration can change this result, but avoid using it as a routine fix because it makes the cascade harder to maintain.
Exercise
An external stylesheet sets p { color: green; }. An internal stylesheet later sets p { color: blue; }, and the element has no inline style. Which color applies?
Show answer
Blue applies because the selectors have equal specificity and the internal declaration appears later.