OneBite.Dev - Coding blog in a bite size

link css file in html

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

CSS, or Cascading Style Sheets, is an essential part of web design as it dictates the look and feel of a webpage. This article offers a brief tutorial on how to link a CSS file in HTML.

Code Snippet

To link your CSS file with the HTML, you need to use the <link> tag. Its placement within your HTML plays a crucial role in the performance of your website, so it is generally placed within the <head> section of the HTML. Here is a simple demonstration:

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
...
</body>
</html>

In the sample above, ‘styles.css’ is the CSS file that we aim to link with our HTML. You can replace ‘styles.css’ with the path and name of your own CSS file.

Code Explanation

Now let’s take a closer look at the code to understand each component.

<!DOCTYPE html>: This is the declaration which tells the browser that this document is an HTML5 document.

<html>: This is the root element of an HTML page.

<head>: The container for metadata (data about data) and other data like a title for the page, scripts, styles, etc.

<link rel="stylesheet" type="text/css" href="styles.css">: This is the main part of linking CSS with HTML, which takes place in the head section.

rel="stylesheet": This attribute specifies the relationship between the current document and the linked document. Here, it’s taking the value stylesheet which indicates that the linked document is a CSS stylesheet to be used for the current HTML document.

type="text/css": This attribute specifies the MIME type of the linked document, which is text/css for CSS files.

href="styles.css": This attribute offers the location and the name of the CSS file you intend to link to your HTML. ‘styles.css’ is the file name and can be replaced with your CSS file name. It’s important to specify the correct path to the CSS file. If the CSS file is in the same folder as the HTML file, you only need to mention the CSS file name.

<body>: Contains the part of the HTML document that will be visible on the webpage.

Remember, CSS helps you design your HTML elements, and linking it correctly to your HTML is a significant step. Happy Coding!

css