Including CSS in HTML Documents


Adding CSS to an HTML document enhances the appearance of the web page. Various styles for the images, borders, margins, colors, can be easily added. To include CSS in HTML documents, we can either include them internally, inline or link an external file. Let us understand them with examples.

Syntax

The syntax for including CSS files in HTML is as follows −

/*inline*/
<element style="/*declarations*/"></element>
/*internal*/
<head>
   <style>
      /*declarations*/
   </style>
</head>
/*external*/
<head>
   <link rel="stylesheet" href="#location">
</head>

The following examples shows the linking of CSS file in HTML Documents −

Inline CSS

With inline CSS, use the style attribute and set the CSS style;

Example

<!DOCTYPE html>
<html>
<body>
   <p style="font-family: Forte;">Demo text</p>
   <p style="background-color: lightblue;">This is Demo text</p>
   <img src="https://www.tutorialspoint.com/memcached/images/memcached.jpg" style="border: 3px groove orange;">
</body>
</html>

Internal linking

For internal linking, the <style> element is used. Under this element, mention the CSS styles −

<style>
   <!--  Add the styles -->
</style>

Example

Let us see the example −

<!DOCTYPE html>
<html>
<head>
   <style>
      div {
         margin: auto;
         padding: 15px;
         width: 33%;
         border: 2px solid;
         border-radius: 5%;
      }
      div > div {
         border-color: transparent;
         box-shadow: inset 0 0 6px red;
      }
      div > div > div {
         border-color: red;
      }
   </style>
</head>
<body>
   <div>
      <div></div>
      <div>
         <div></div>
      </div>
      <div></div>
   </div>
</body>
</html>

External linking

On a web page, you can also include an external css file and place the css styles in it. The same CSS file can be referred from the HTML file as shown in the below example. The <link> element is used to link an external file style.css −

<link rel="stylesheet" type="text/css" href="style.css">

Example

Let us see the example −

<!DOCTYPE html>
<html>
<head>
   <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
   <p>Demo text</p>
   <p>Demo text again</p>
</body>
</html>

The following is the external style.css file −

p {
   text-decoration: overline;
   text-transform: capitalize;
}

Updated on: 21-Dec-2023

104 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements