Introduction to CSS (Cascading Style Sheets)

Learn CSS basics with examples of inline, internal, and external styles. Improve your web pages with clean, responsive design.
Introduction to CSS (Cascading Style Sheets)

CSS (Cascading Style Sheets) is a style sheet language used to control the look and feel of web pages. While HTML provides the structure, CSS is used to style and design the content, including colors, fonts, layouts, and responsiveness.

Why Use CSS?

  • Separation of concerns: Keep design separate from structure.
  • Consistency: Apply the same styles across multiple pages.
  • Reusability: One CSS file can be linked to many HTML pages.
  • Better user experience: Makes websites more attractive and responsive.

How to Add CSS to HTML

There are three main ways to include CSS in your HTML:

  1. Inline CSS: Added directly in the HTML element using the style attribute.
  2. Internal CSS: Defined inside a <style> block within the <head> section.
  3. External CSS: Written in a separate .css file and linked to HTML using <link>.

Example: Inline CSS

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Inline CSS Example</title>
</head>
<body>
  <h1 style="color:blue; text-align:center;">Hello, CSS!</h1>
</body>
</html>

Example: Internal CSS

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Internal CSS Example</title>
  <style>
    body {
      background-color: #f4f4f4;
      font-family: Arial, sans-serif;
    }
    h1 {
      color: green;
      text-align: center;
    }
  </style>
</head>
<body>
  <h1>Welcome to CSS!</h1>
</body>
</html>

Example: External CSS

HTML File (index.html):

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>External CSS Example</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <h1>Styled with External CSS</h1>
</body>
</html>

CSS File (style.css):

body {
  background-color: #fafafa;
  font-family: Verdana, sans-serif;
}
h1 {
  color: crimson;
  text-align: center;
}

CSS Syntax Basics

A CSS rule is made up of a selector and a set of declarations.

selector {
  property: value;
}

Example:

h1 {
  color: blue;
  font-size: 24px;
}

Conclusion

CSS is a powerful tool for controlling the visual presentation of web pages. By separating structure (HTML) from style (CSS), developers can create clean, professional, and responsive websites.

Post a Comment