CSS How To

How to Add CSS to HTML

CSS (Cascading Style Sheets) styles and formats HTML documents.

There are three main ways to add CSS to your HTML:

1. Inline CSS

Inline CSS is used to apply styles directly to a single HTML element. This is done using the style attribute within the element.

Example:

<p style=”color:blue”>Hello CSS</p>

Output:
css-how-to-Inline-CSS
In this example:

style=”color: blue;”: This inline style directly applies the CSS property color with the value blue to the paragraph (<p>) element.

Advantages:

• Immediate and specific: Applies styles directly to individual elements.
• High specificity: Inline styles override any other CSS rules.

Disadvantages:

• Not scalable: Difficult to manage and maintain for large websites.
• Clutters HTML: Makes the HTML code messy and harder to read.

2. Internal CSS

Internal CSS is used to apply styles to a single HTML document. The CSS rules are defined within a <style> tag inside the <head> section of the document.

Example:
Output:
css-how-to-Internal-CSS
In this example:

The <style> tag is used within the <head> section to define CSS rules.
• p { color: blue; }: This CSS rule targets all <p> elements and sets their text color to blue.

Advantages:

• Contained within the HTML file: Keeps styles and content together.
• Good for single pages: Effective for styling a single page or document.

Disadvantages:

• Not ideal for multiple pages: Not efficient for applying styles across multiple documents.
• Increases file size: Adds to the size of the HTML file.

3. External CSS

External CSS is used to apply styles to multiple HTML documents. The CSS rules are written in a separate file with a .css extension, and this file is linked to the HTML documents using a <link> tag inside the <head> section.

Example:

HTML file (index.html):

<!DOCTYPE html>
<html>
<head>
    <link rel=”stylesheet” type=”text/css” href=”styles.css”>
</head>
<body>
    <p>This is a paragraph styled with external CSS.</p>
</body>
</html>

HTML file (index.html):

p {
color: blue;
}

Output:
In this example:

The <link> tag in the <head> section of your HTML file links to the external CSS file. The rel=”stylesheet” attribute specifies the relationship between the HTML file and the CSS file, while the href attribute specifies the path to the CSS file.
The styles.css file contains the CSS rule that targets all <p> elements and sets their text color to blue.

Advantages:

• Highly scalable: Efficient for large websites with multiple pages.
• Reusability: Styles can be reused across different HTML documents.
• Keeps HTML clean: Separates content from styling, making the HTML code cleaner and easier to maintain.

Disadvantages:

• Requires additional file: An extra HTTP request is needed to load the CSS file.
• Dependent on external file: Styles will not be applied if the CSS file is inaccessible.

Course Video

Course Video in English