Styling HTML with CSS

CSS is often added to HTML to adjust the appearance of elements on the page, we'll be taking a look at the three methods that can be used to apply CSS to our HTML.

In the examples below I demonstrate how the inline, internal, and external approaches to adding CSS can be used to apply simple styles to a paragraph element. While each approach adds the styles in a different way they all result in following bold purple text:

We're Stylin' Now!

Inline

Inline styles are written directly in the desired element's style attribute, and are used to uniquely style a single element. It should be noted that inline styles have the highest priority in CSS and will override any competing styles defined in internal or external style sheets.

HTML
<!DOCTYPE html>
<html>
<body>
<p style="color: indigo; font-weight: bold">We're Stylin' Now!</p>
</body>
</html>

Internal

Internal styles are defined in the <head> of an HTML document within a <style> element, and only apply to elements on that particular page. While Internal styles have lower precedence and will be overridden by inline styles, they have higher precedence and will override any competing styles in external style sheets.

HTML
<!DOCTYPE html>
<html>
<head>
<style>
p {
color: indigo;
font-weight: bold;
}
</style>
</head>
<body>
<p>We're Stylin' Now!</p>
</body>
</html>

External

External styles are, as their name suggests, defined in a separate .css file. These styles can then be brought into one or many distinct HTML pages by adding a <link> element with a path to the file in the <head> section of the desired page.

This approach is the most common, since as you can imagine it's easier to maintain and adjust a few external css files than it would be to adjust every page's internal styles or individual elements styles whenever we wanted to make css changes.

HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<p>We're Stylin' Now!</p>
</body>
</html>
CSS
/* styles.css (External File)
* Here it's named "styles" but the name can be whatever
* you want as long as it ends with the .css extension
*/
p {
color: indigo;
font-weight: bold;
}

Note: External CSS is the most flexible, but it also has the lowest specificity which means any competing inline or internal styles will naturally override styles defined externally.

Published: Aug 19th, 2019

Updated: Aug 20th, 2019