CSS (Cascading Style Sheets) can be applied to HTML documents in three different ways: inline, internal, and external. Each approach has its own advantages and use cases.
Inline CSS is applied directly within individual HTML elements using the style attribute. This method is useful for applying quick, specific styling to a single element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inline CSS</title>
</head>
<body>
<p style="color: blue; font-size: 16px;">This is a blue text with a font size of 16px.</p>
</body>
</html>
Pros:
• Quick and easy to implement for small changes.
• Overrides other CSS rules for that specific element.
Cons:
• Mixing presentation with content can lead to maintenance challenges.
• Limited reusability and consistency across multiple elements or pages.
Internal CSS is defined within the <style> tag in the <head> section of an HTML document. It applies styles to elements within that particular HTML file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Internal CSS</title>
<style>
p{color: red; font-size: 20px;}
</style>
</head>
<body>
<p>This is a red text with a font size of 20px.</p>
</body>
</html>
Pros:
• Allows for more organized styling within a single HTML file.
• Better separation of content and presentation compared to inline CSS.
Cons:
• Limited reusability across multiple HTML files.
• Can become cluttered and hard to manage for larger projects.
External CSS is stored in a separate .css file and linked to HTML documents using the <link> element. This is the most common and recommended approach for larger projects.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>External CSS</title>
</head>
<body>
<p class="text-red">This is a red text.</p>
</body>
</html>
.text-red{
color: red;
}