As coders who have just learned CSS, we first start to incorporate CSS to our web pages as inline-styling. We use the style attribute to inject the CSS directly on our HTML element:
<!DOCTYPE html> <html> <head> <title>Inline Style</title> </head> <body> <h1 style="color:blue;text-align:center;">Star Wars</h1> <h4 style="color:red;text-align:center;">Return of the Jedi</h4> </body> </html>
As we move to more complicated sites, we move to incorporating our CSS as Internal CSS. This is where we write all of our CSS in between <style>
tags in the <head>
section of the HTML document:
<!DOCTYPE html> <html> <head> <title>Internal CSS</title> <style> h1, h4 { text-align: center; } h1 { color: blue; } h4 { color: red; } </style> </head> <body> <h1>Star Wars</h1> <h4>Return of the Jedi</h4> </body> </html>
This cleans up our HTML nicely. However, what if we had 500 lines of CSS? This file would get hard to read pretty quickly. However, we have the ability to create external stylesheets and then link them to our HTML file!
The Setup:
- In your main project folder where your index.html file is, create a new file called index.css. The index.css file is going to hold all of the CSS for our index.html file. I like to name my CSS files after the HTML files they style to keep things organized, but you can certainly name them whatever you’d like as long as you know which files they are styling.
- If you have CSS in between the
<style>
tags in the<head>
of your HTML file, cut and paste the CSS code only (no tags) into the corresponding CSS file. - In the
<head>
of your HTML file, you are going to create a <link> tag that points to your CSS file:
<link rel="stylesheet" type="text/css" href="./index.css">
The link is made up of three parts:
- The rel attribute: This tells us there is going to be a relationship between this file and another file, and this link will tell us what that relationship is.
- The type attribute: Describes the type of relationship the linked file has to the HTML file.
- The href attribute: The relative path to the file from where the HTML file is – the file’s location.
Remember that even though we are separating the CSS file from the HTML file, the cascading nature of CSS still reigns supreme. This means if you have multiple CSS files, you will need to:
1. Have a <link> pointing to each individual CSS file.
2. Make sure those files are in the order you need them to be so the proper styling shows. If they are not in the proper order, the styling may not work.
That’s all there is to it. You are now well on your way to creating external stylesheets for your project!
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.