Skip to main content

How to Insert CSS Stylesheet in HTML

In this Section, we'll go through different ways of inserting CSS into an HTML document. CSS is a powerful styling language that allows you to make your web pages look beautiful and visually appealing. While you can write CSS code directly in your HTML file, it is always advisable to write your CSS code in a separate external file to make your code more maintainable, readable, and scalable.

There are several ways to insert CSS into an HTML file, and each method has its own advantages and disadvantages.

Ways to insert CSS into an HTML document

  • Inline CSS
  • Internal CSS
  • External CSS

1. Inline CSS

The first and most basic way to add CSS to an HTML document is through inline styles. Inline styles are applied directly to an HTML element using the style attribute. Here's an example:

<!DOCTYPE html>
<html>
<head>
<title>My Webpage</title>
</head>
<body>
<!-- inline css -->
<h1 style="color: red; font-size: 24px;">Hello World!</h1>
</body>
</html>

In the above example, we added inline CSS to the h1 element to change its color to red and font-size to 24px.

caution

While inline styles are easy to add, they can quickly become unwieldy and hard to maintain in larger projects.

2. Internal CSS

<!DOCTYPE html>
<html>
<head>
<title>My Webpage</title>
<!-- internal CSS -->
<style>
h1 {
color: red;
font-size: 24px;
}
</style>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>

In the above example, we defined internal CSS for the h1 element by placing the CSS code inside the style tag.

info

The advantage of internal styles is that you can define styles for multiple elements in one place.

3. External CSS

The third and most recommended way to add CSS to an HTML document is through external stylesheets. External stylesheets are defined in a separate file with a .css extension, and then linked to the HTML document using the link tag. Here's an example:

Folder Structure Example :-

my-app
├── src
│ ├── style.css
│ ├── helloWord.html

We will add a separate CSS file called style.css to the helloWorld.html file. This will make our code more organized and easier to manage. To add the CSS file to the HTML file, follow the steps below:

  1. Create a new file in 'src' folder of my-app project called style.css
style.css
  h1 {
color: red;
font-size: 24px;
}
  1. In the helloWorld.html file, add the style.css.
helloWord.html
<!DOCTYPE html>
<html>
<head>
<title>My Webpage</title>
<!-- style.css added-->
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>

In the above example, we linked an external stylesheet named style.css to our HTML document using the link tag. The stylesheet contains CSS code that applies to the HTML document.

tip

The advantage of external stylesheets is that they can be reused across multiple pages, and it's easy to maintain and update the styles.