Connecting CSS to HTML

This article came as a result of helping a friend (a new developer) troubleshoot their way through one of their early projects. The problem, in essence, was the CSS style sheet within the app was not connected to their HTML code. So here, I’ll go through 3 ways to connect CSS to HTML documents.

External CSS

So the first one covered is typically the most common, using an external CSS file completely separate from the HTML document. For the purposes of this example, we’re going to consider the HTML document titles “mydocument.html”, and the CSS file titles “stylesheet.css”. First, lets take a quick look at how the code looks:

External CSS

So this shows a basic outline of an HTML document, with the stylesheet.css file linked. Notice it is linked in the <head> attribute of the file, as the placement within the head is very important. Once the CSS file is linked this way, the styling from the CSS file should be implemented through the HTML file it is attached to.

Internal CSS

The second way is similar to the first, but involves a bit more connections between the two styles, as shown below:

Internal CSS

Similar to the External option above, the CSS is still stored in the <head> attribute, but unlike the External option, the instructions for CSS are written directly into the HTML file, as opposed to in a file stored elsewhere. I should be noted that even though the CSS instructions are written into an HTML file, CSS is still written in the same style as if they were in a different file

Inline CSS

Our third and final way to write CSS into our HTML files is using what’s called CSS. Now this is really only used in instances where the CSS instructions are not being repeated, because it would lead to a lot of repeat coding if they were. Typically, inline CSS looks like this:

Inline CSS

In this case, you can see each HTML tag has its style set in the line as the tag, as opposed to in the header, as with the previous two examples. As mentioned before, if each element were to be styled the same, either of the previous two would be preferred, for both readability and ease of use for the programmer. Though all three of these techniques would provide similar results in styling, it is generally preferred to use External CSS anytime you can when programming.

Flatiron School DC. Learning to code one day at a time.