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:
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:
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
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, we write our CSS rules:
Then we can import
index.cssto HTML with a <link> tag like below:
<head> <link rel="stylesheet" type="text/css" href="index.css"> </head> <body> <h1> Test Headline </h1> </body>
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!
I’m a Software Engineer with experience in Frontend Web Development.
I’m currently employed in Germany and working on a project with React JS. On my free time, I like to write about technologies, programming languages, tools and my experiences about Frontend Development.
Feel free to follow me on my other social media profiles below.