FullStackCamp

Coding

Marketing

Prompts

Tools

What is CSS

Introduction to CSS

CSS (Cascading Style Sheets) is a stylesheet language used to control the appearance and layout of web pages. It works alongside HTML to define how elements look, including colors, fonts, spacing, and positioning, enabling visually appealing and responsive designs.

  • Purpose: Styles HTML content to enhance user experience and aesthetics.
  • Role in Web Development: Complements HTML (structure) and JavaScript (interactivity).

Example: Basic CSS styling:

<!DOCTYPE html>
<html>
<head>
    <style>
        h1 { color: blue; }
        p { font-size: 16px; }
    </style>
</head>
<body>
    <h1>Welcome</h1>
    <p>This is styled text.</p>
</body>
</html>

CSS Syntax

CSS consists of rules that target elements and apply styles. A rule includes a selector (what to style) and a declaration block (how to style).

  • Selector: Targets HTML elements (e.g., h1, .class, #id).
  • Declaration: Property-value pair (e.g., color: blue;).
  • Syntax: selector { property: value; }.

Example: CSS rule:

p {
    color: green;
    margin: 10px;
}

Ways to Apply CSS

CSS can be integrated into HTML in three ways:

  • Inline CSS: Styles applied directly in an element’s style attribute.
    • Use sparingly due to maintenance challenges.
  • Internal CSS: Styles defined in a <style> tag within the <head>.
    • Suitable for single pages.
  • External CSS: Styles in a separate .css file linked via <link>.
    • Best for scalability and reuse.

Example: All three methods:

<!DOCTYPE html>
<html>
<head>
    <!-- External CSS -->
    <link rel="stylesheet" href="styles.css">
    <!-- Internal CSS -->
    <style>
        p { font-style: italic; }
    </style>
</head>
<body>
    <!-- Inline CSS -->
    <h1 style="color: red;">Heading</h1>
    <p>Paragraph text.</p>
</body>
</html>
/* styles.css */
h1 { text-align: center; }

The Cascade and Specificity

CSS follows a cascade, where styles are applied based on their source and specificity:

  • Cascade Order: Inline > Internal > External > Browser defaults.
  • Specificity: More specific selectors (e.g., #id > .class > tag) take precedence.
  • !important: Overrides other styles (use cautiously).

Example: Specificity in action:

<style>
    p { color: blue; }
    .highlight { color: red; }
    #special { color: green; }
</style>
<p>Blue text</p>
<p class="highlight">Red text</p>
<p id="special" class="highlight">Green text</p>

Best Practices for CSS

  • Use External Stylesheets: Keep styles separate for maintainability.
  • Write Readable Code: Use consistent indentation and comments.
  • Avoid !important: Rely on specificity instead.
  • Test Cross-Browser: Ensure styles render consistently.

Example: Organized external CSS:

/* styles.css */
body {
    font-family: Arial, sans-serif;
    margin: 0;
}

h1 {
    color: navy;
    text-align: center;
}
<link rel="stylesheet" href="styles.css">
<h1>Welcome</h1>