Introduction to CSS: Styling the Web

Introduction to CSS: Styling the Web

Introduction to CSS: Styling the Web

What is CSS?

CSS, or Cascading Style Sheets, is a stylesheet language used to describe the presentation of a document written in HTML or XML. While HTML structures the content on the web, CSS is what makes it look appealing. It controls the layout of multiple web pages all at once.

Why Learn CSS?

  • Separation of Concerns: CSS allows you to separate the content (HTML) from the presentation (CSS). This makes it easier to maintain and update your website.
  • Consistency: With CSS, you can apply a consistent style across multiple web pages, ensuring a uniform look and feel.
  • Flexibility: CSS gives you control over various design aspects like fonts, colors, spacing, and layout, enabling you to create visually appealing websites.

Basic Structure of CSS

CSS is made up of rules, and each rule consists of a selector and a declaration block.

  • Selector: The HTML element you want to style.
  • Declaration Block: Contains one or more declarations separated by semicolons. Each declaration includes a CSS property name and a value, separated by a colon.

Here's a simple example:


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

In this example:

  • h1 is the selector, targeting all <h1> elements in the HTML.
  • color: blue; and font-size: 24px; are declarations, setting the text color to blue and the font size to 24 pixels.

How to Add CSS to HTML

There are three ways to apply CSS to HTML: Inline, Internal, and External.

Inline CSS

Inline CSS is used to apply a unique style to a single HTML element. It is added directly within the HTML tag using the style attribute.


<p style="color: red;">This is a red paragraph.</p>
        

Internal CSS

Internal CSS is used to define styles for a single HTML document. It is placed within the <style> element, inside the <head> section of the HTML file.


<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      background-color: lightblue;
    }
    p {
      color: green;
    }
  </style>
</head>
<body>
  <p>This is a green paragraph on a light blue background.</p>
</body>
</html>
        

External CSS

External CSS is used to apply styles to multiple HTML documents. It is linked to the HTML file using the <link> element within the <head> section. The CSS rules are written in a separate .css file.

HTML File:


<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
  <h1>Welcome to My Website</h1>
  <p>This is a paragraph.</p>
</body>
</html>
        

CSS File (styles.css):


body {
  background-color: lightgray;
}
h1 {
  color: navy;
}
p {
  color: darkgreen;
}
        

Conclusion

CSS is an essential tool for web developers, enabling you to create visually stunning and user-friendly websites. By mastering the basics of CSS, you can start styling your web pages to match your creative vision. Happy coding!