MakeW3web

The Style Element and Link Element

The `<style>` and `<link>` elements are used to apply CSS to an HTML document. They serve different purposes and are used in different situations when working with CSS styles.

  1. The `<style>` element: The `<style>` element is used to include internal CSS styles directly within an HTML document. It is placed inside the `<head>` section of the document, and the CSS rules are written between the opening and closing `<style>` tags. These internal styles apply to the elements within the same HTML document.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Using the Style Element</title>
  <style>
    h1 {
      color: blue;
    }
    p {
      font-size: 14px;
    }
  </style>
</head>
<body>
  <h1>Heading styled with internal CSS</h1>
  <p>Paragraph styled with internal CSS</p>
</body>
</html>
  1. The `<link>` element: The `<link>` element is used to link an external CSS file to your HTML document. The external CSS file contains your CSS styles, and the `<link>` element establishes the relationship between the HTML document and the CSS file. This way, you can apply consistent styles across multiple HTML documents using a single CSS file. The `<link>` element is placed inside the `<head>` section of the HTML document and uses the `rel`, `href`, and `type` attributes to link the CSS file.

Example:

Create an external CSS file called `styles.css`:

/* styles.css */
h1 {
  color: red;
}
p {
  font-size: 16px;
}

Link the CSS file in your HTML document:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Using the Link Element</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <h1>Heading styled with external CSS</h1>
  <p>Paragraph styled with external CSS</p>
</body>
</html>

In summary, the `<style>` element is used for internal CSS styles within an HTML document, while the `<link>` element is used to link an external CSS file to the HTML document. Using external CSS files with the `<link>` element is recommended for most projects, as it keeps your styles organized and makes it easier to maintain and update styles across multiple HTML documents.

Was this page helpful?