How to use CSS with HTML


Using CSS with HTML is a great way to style your web pages. There are three main ways to include CSS in your HTML:

1. Inline CSS

You can apply CSS styles directly within an HTML element using the style attribute. This method is useful for quick, one-off styles but isn't ideal for larger projects.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Inline CSS Example</title> </head> <body> <h1 style="color: blue; text-align: center;">Hello, World!</h1> </body> </html>

2. Internal CSS

You can include CSS rules within a <style> block in the <head> section of your HTML document. This method is useful for styling a single document.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Internal CSS Example</title> <style> body { font-family: Arial, sans-serif; } h1 { color: green; text-align: center; } </style> </head> <body> <h1>Hello, World!</h1> </body> </html>

3. External CSS

You can place CSS in a separate .css file and link to it from your HTML document. This method is ideal for larger projects because it separates content from design.

style.css:

body { font-family: Arial, sans-serif; } h1 { color: red; text-align: center; }

index.html:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>External CSS Example</title> <link rel="stylesheet" href="style.css"> </head> <body> <h1>Hello, World!</h1> </body> </html>

Which Method to Use?

  • Inline CSS is quick for small changes but not scalable.
  • Internal CSS is good for single pages or specific sections.
  • External CSS is best for maintaining styles across multiple pages and keeping your HTML cleaner.