Signup/Sign In
LAST UPDATED: AUGUST 5, 2021

How to add CSS within the HTML document?

CSS (Cascading Style Sheet) is used styling HTML web pages. It adds spacing, controls the position and display of elements, etc. In this tutorial, we will be learning to add CSS within the HTML document.

Ways to add CSS to HTML document

There are three ways to add CSS to the HTML document. We will be discussing all three ways one by one.

1. Inline Styling

In the inline styling, we can add CSS codes to the HTML tag itself. The CSS is added by using the style attribute. It can be used to style a single element. It is the simplest method but it is not recommended to use for building websites.

Example: Add CSS using inline Styles

In this example, we have used inline CSS to style each HTML element.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
</head>
<body>
   <h2 style="text-align:center; color: blue"> Inline styles </h2>
   <p style="text-align:center; color:green; font-size:22px"> Here we have used inline method to style paragraph</p> 
</body>
</html>

Output

Here is the output of the above code.

using inline CSS

2. Internal styles

Internal CSS or embedded CSS is used to style the elements of a single page. The CSS codes are added within <style> tag. The style tag should be added within the <head> section of the HTML document.

Example: Style elements using internal CSS

Here, we have used internal CSS to style the HTML element.

External Styles

The external styles are used to define styles for many web pages or a whole website. For external styles, CSS styles are documented in a separate file and the link is added to the <head> section. The file link is added to the <link> tag. The file with CSS styles should be saved with the .css extension.

Example: Style HTML elements using external CSS

Here, we have defined CSS in the style.css file.

h2 {
     color: blue;
	 font-size: 22px;
  }
p {
    text-align: left;
	color: red;
	font-size: 22px;
}
button {
     background: cyan;
	 padding: 10px;
	 margin: 3px;
}

And then add the link to the head section of the HTML document.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
   <h2> External styles </h2>
   <p> We have added External styles to our HTML document </p> 
   <button> Click Here </button>
</body>
</html>

Output

Here is the output of the above program.

external css

Conclusion

We discussed all three ways to add CSS styles to the HTML elements. For styling, a single element use inline styles, for a single page uses internal styles, and for styling, more than one page uses an external document. You can refer to our detailed article on CSS Styling.



About the author: