Computer >> Computer tutorials >  >> Programming >> CSS

How to include CSS in HTML Pages


We can include CSS in HTML pages in three ways. These are −

  • Inline

    Here we specify CSS styles in the style attribute of element. However, it is recommended to internal or external linking of CSS to modularize files.

  • Internal

    We can include our CSS specifications in the <style> tag inside <head> of the HTML document.

  • External

    We can link .css files which may be placed locally or on server using the <link> tag. Refactoring files by using external linking of files allows us to have a common CSS file which can be used across multiple webpages.

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>

Example

The following examples illustrate how CSS files are include in HTML pages

Inline CSS

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div style="background-color:mistyrose; height: 50px;"></div>
<p style="letter-spacing: 16px; font-size: 1.3em;">
<u>Demo text here</u>
</p>
</body>
</html>

Output

This gives the following output −

How to include CSS in HTML Pages

Example

Internal linking

<!DOCTYPE html>
<html>
<head>
<style>
table, table *{
   border: 5px double green;
   margin: auto;
   padding: 20px;
}
tr {
   box-shadow: 0 0 0 3px red;
}
td {
   border-color: blue;
}
</style>
</head>
<body>
<table>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>

Output

This gives the following output −

How to include CSS in HTML Pages

Example

External linking

HTML file

<!DOCTYPE html>
<html>
<head>
<link rel=”stylesheet” type=”text/css” href=”style.css”>
</head>
<body>
<div>
<div></div>
<div>
<div></div>
</div>
<div></div>
</div>
</body>
</html>

CSS file

div {
   margin: auto;
   padding: 15px;
   width: 33%;
   border: 2px solid;
   border-radius: 50%;
}
div > div {
   border-color: green;
}
div > div > div {
   border-color: red;
}

Output

This gives the following output −

How to include CSS in HTML Pages