OneBite.Dev - Coding blog in a bite size

import css in html

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

Adding CSS to our HTML documents is a crucial step in web development, letting us stylize webpages and create beautiful, user-friendly interfaces. This article guides you through the simple yet fundamental process of importing CSS into HTML.

Code snippet for CSS import in HTML

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

Code Explanation for CSS import in HTML

Step 1: To begin with, let’s understand the basic structure of an HTML document, which consists of a <html> tag as a container for the whole HTML document, a <head> tag, which contains meta-information about the document, and a <body> tag, including the contents to be displayed to the user.

Step 2: We will now focus on the <link> tag nested inside the <head> of our HTML document. This is where the magic happens as we will use this to connect our CSS file.

Step 3: The <link> tag contains three main attributes – rel, type, and href.

  • rel: This defines the relationship between our HTML and the file we are linking to. By setting it to “stylesheet”, we tell the browser that the linked file is a CSS file used to style the webpage.
  • type: The “type” attribute specifies the MIME type of the linked file. Since we are linking a CSS file, we use type="text/css".
  • href: This is simply the location of the file we are importing. For the demonstration’s sake, we have a CSS file (styles.css) that is in the same directory as our HTML file. Hence, we set href attribute to href="styles.css". If your CSS file is nested within a folder or located elsewhere, you’ll have to adjust the href attribute accordingly.

Step 4: Inside the <body> tag, we have a simple <div>, denoted by the set of <div> tags. Inside this division, we have a simple text: “Hello, World!“. The <div> tag is a vanilla HTML tag that contributes nothing more than being a generic container for our content.

In conclusion, we can import CSS into HTML with the help of the <link> tag placed within the <head> tag of HTML. This organizes our project files better and makes code debugging easier. It’s also the standard practice for web development, setting us up on the right path to creating visually stunning websites.

css