OneBite.Dev - Coding blog in a bite size

use a css file in html

Code snippet for how to use a css file in html with sample and detail explanation

Title: Using a CSS File in HTML

Incorporating CSS files in HTML is a common method used by web developers to enhance the aesthetics and functionality of websites. This article will guide you through a simple step-by-step process on how to link and use CSS files in HTML.

Code Snippet: Linking a CSS File to HTML

Here is an essential snippet of HTML and CSS where we link a CSS file to our HTML:

HTML file (index.html):

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
    <h1>Welcome to my Website!</h1>
    <p>This is a paragraph</p>
</body>
</html>

CSS file (styles.css):

body {
    background-color: lightblue;
}

h1 {
    color: navy;
    margin-left: 20px;
}
p {
   color: red;
}

Code Explanation for Linking a CSS File to HTML

In the HTML snippet, the <link> element within the <head> tags is used to connect the CSS file to the HTML file. This link element has 3 important attributes:

  • rel: Defines the relationship between the HTML and linked resource. In this case, it hints that the linked resource is a ‘stylesheet’.
  • type: Indicates the MIME type of the linked resource. For a CSS file, this is ‘text/css’.
  • href: Specifies the location of the linked file. In our example, it’s ‘styles.css’, implying the CSS file is in the same directory as our HTML file.

In the CSS snippet, the styles for the HTML body, the <h1> tag, and the <p> tag are defined. When the HTML and CSS files are linked, the CSS styles are applied to the corresponding HTML elements bringing about a styled webpage.

This is the basic idea behind using a CSS file in HTML. By incorporating this method into your projects, you’ll be able to create more structured and attractive web pages. Remember, practice is essential in perfecting your web design skills. Happy coding1

css