3 Ways for Adding CSS into HTML

Coding Docs CSS

CSS rules start working after they are being added to HTML. There are a couple of ways for adding CSS into HTML and in this article, you’re going to learn how to do it in 3 different ways.

If you prefer, you can also watch the video version of this post from my channel:

1. Inline-Style

The first way to add CSS into HTML is by using a method called inline-styling. Inline-style means adding CSS rules directly into the HTML elements (tags) with the style attribute.

For example, if I want to change the text color of an element:

<h1 style="color: red">Test Headline</h1>
  • First I need to add a style attribute to that specific element
  • Then inside the quotes, I can define one or more CSS rules like above

Then the new rule (text color here) for the h1 element will be applied:

However in daily programming, we don’t want to use inline-styles, because it only targets a single HTML element, instead of targeting multiple, is not easily searched and found in larger projects, and the most important reason is that we can’t keep our CSS code separate from HTML.

We don’t prefer to use inline styles in daily programming.

2. Internal CSS

The second way for adding CSS to HTML is by using the internal CSS way. In order to use this way, we need to use an HTML tag called <style> tag (not style attribute) and between the style tags, we can write our CSS selectors & rules:

color: red;
<h1>Test Headline</h1>

So this is the second approach for adding CSS into our HTML file, but it’s still not perfect because what we like to do is to keep HTML and CSS in separated files, which leads us to the third way.

3. External CSS

Keeping CSS & HTML separated is best practice. In real programming, we need to keep HTML, CSS, and JavaScript in separate files and later import them where necessary. This way improves readability & makes it easier for the maintenance of the code.

To use this way, we need to create separate CSS files with an extension of .css and later link them to HTML.

For example, we can create a CSS file like this one: index.css. Inside index.css, we write our CSS rules:

h1 {  
color: red;

Then we can import index.cssto HTML with a <link> tag like below:

   <link rel="stylesheet" type="text/css" href="index.css">
 <h1> Test Headline </h1>

And the rules are again applied successfully:

Using external CSS files and link/import them to HTML is the commonly preferred way.

So these are the 3 ways for adding CSS into our HTML. In the next article, I will cover CSS selectors, which is a really important part to understand the basics of CSS.

If you want to learn more about web development, feel free to subscribe to our newsletter.

Thank you for reading!

Leave a Reply

Your email address will not be published. Required fields are marked *