CSS Introduction | Getting Started with CSS | Applying CSS
How to Apply CSS
There are three ways to apply CSS styles to an HTML document.
- Inline style
- Internal style sheet
- External style sheet
Inline Style
An inline style applies CSS by using the style attribute inside an HTML element.
This kind of inline style applies only to the specific element.
<body>
<h2 style="color:green; text-decoration:underline">
The style was applied with an inline style.
</h2>
</body>
This approach makes styles very difficult to change once they are set and loses many benefits of using style sheets. Therefore, use this approach only when it is truly necessary.
Internal Style Sheet
An internal style sheet applies CSS by using the <style> tag inside the <head> tag of an HTML document.
This kind of internal style sheet applies only to the corresponding HTML document.
<head>
<style>
body { background-color: lightyellow; }
h2 { color: red; text-decoration: underline; }
</style>
</head>
External Style Sheet
An external style sheet lets you change the style of an entire website from a single file.
These external style sheet files are saved with the .css extension.
To apply the style, include the external style sheet with the <link> tag inside the <head> tag of the web page.
<head>
<link rel="stylesheet" href="/examples/media/expand_style.css">
</head>
The CSS file used in the example above contains the following.
expand_style.css
body { background-color: lightyellow; }
p { color: red; text-decoration: underline; }
Priority of Style Application
When the style application methods above are mixed, the final style is determined in the following order.
- Inline styles, located inside HTML elements
- Internal and external style sheets, located inside the
headelement of the HTML document - Default web browser styles
For example, a tag with an inline style always uses the inline style regardless of internal or external style sheets. For internal and external style sheets, the style sheet applied last takes effect.
<link rel="stylesheet" href="/examples/media/expand_style.css">
...
<h2>Only the external style sheet is applied to this part.</h2>
<h2 style="color:maroon; text-decoration:line-through"> Both the inline style and the external style sheet are applied to this part. </h2>
Therefore, using external style sheets is the most maintainable and stable way to apply styles to a website.