CSS Syntax and Selectors

Week 1, Day 3 - Lecture 1

Welcome to CSS!

If HTML is the skeleton of a web page, CSS (Cascading Style Sheets) is the skin, clothes, and makeup. It's what makes websites beautiful, professional, and unique. Imagine building a house - HTML provides the structure, but CSS adds the paint, wallpaper, and decorations!

graph LR A[HTML] -->|Structure| B[Web Page] C[CSS] -->|Style| B D[JavaScript] -->|Behavior| B style A fill:#f9f,stroke:#333,stroke-width:2px style C fill:#9f9,stroke:#333,stroke-width:2px style D fill:#ff9,stroke:#333,stroke-width:2px style B fill:#9ff,stroke:#333,stroke-width:4px

Three Ways to Add CSS

1. Inline CSS

<p style="color: blue; font-size: 16px;">This is blue text.</p>

👎 Not recommended: Hard to maintain, violates separation of concerns

2. Internal CSS

<head>
    <style>
        p {
            color: blue;
            font-size: 16px;
        }
    </style>
</head>

👍 Better: Good for single-page styles or quick prototypes

3. External CSS

<head>
    <link rel="stylesheet" href="styles.css">
</head>

👍👍 Best practice: Reusable, maintainable, cacheable

graph TD A[CSS Methods] --> B[Inline CSS] A --> C[Internal CSS] A --> D[External CSS] B --> E[style attribute] C --> F[style element] D --> G[link element] E --> H[Single element] F --> I[Single page] G --> J[Multiple pages] style B fill:#fdd,stroke:#333,stroke-width:2px style C fill:#ffd,stroke:#333,stroke-width:2px style D fill:#dfd,stroke:#333,stroke-width:2px

CSS Syntax

CSS is written as a series of rules. Each rule has a selector and a declaration block:

selector {
    property: value;
    property: value;
    property: value;
}

Anatomy of a CSS Rule

h1 {
    color: blue;
    font-size: 24px;
    text-align: center;
}
graph LR A[h1] --> B[Selector] C["{"] --> D[Declaration Block Start] E["color: blue;"] --> F[Declaration] G["font-size: 24px;"] --> H[Declaration] I["}"] --> J[Declaration Block End] F --> K[Property] F --> L[Value] style A fill:#f9f,stroke:#333,stroke-width:2px style E fill:#9ff,stroke:#333,stroke-width:2px style K fill:#ff9,stroke:#333,stroke-width:2px style L fill:#9f9,stroke:#333,stroke-width:2px

CSS Comments

/* This is a CSS comment */

/* 
   Multi-line comments
   are also supported
*/

/* TODO: Update these colors */

CSS Selectors

Selectors are patterns used to select the elements you want to style. Think of them as search queries for HTML elements!

Basic Selectors

1. Element Selector

/* Selects all p elements */
p {
    color: blue;
}

/* Selects all h1 elements */
h1 {
    font-size: 32px;
}

2. Class Selector

/* Selects elements with class="highlight" */
.highlight {
    background-color: yellow;
}

/* Selects elements with class="error-message" */
.error-message {
    color: red;
    border: 1px solid red;
}

HTML: <p class="highlight">Highlighted text</p>

3. ID Selector

/* Selects element with id="header" */
#header {
    background-color: navy;
    color: white;
}

/* Selects element with id="main-nav" */
#main-nav {
    position: fixed;
    top: 0;
}

HTML: <div id="header">Header content</div>

4. Universal Selector

/* Selects all elements */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
graph TD A[CSS Selectors] --> B[Element] A --> C[Class] A --> D[ID] A --> E[Universal] B --> F["p, div, h1"] C --> G[".classname"] D --> H["#idname"] E --> I["*"] style B fill:#9cf,stroke:#333,stroke-width:2px style C fill:#fc9,stroke:#333,stroke-width:2px style D fill:#cf9,stroke:#333,stroke-width:2px style E fill:#c9f,stroke:#333,stroke-width:2px

Combining Selectors

1. Descendant Selector

/* Selects all p elements inside div elements */
div p {
    margin-bottom: 10px;
}

/* Selects all a elements inside nav elements */
nav a {
    text-decoration: none;
    color: white;
}

2. Child Selector

/* Selects p elements that are direct children of div */
div > p {
    font-weight: bold;
}

/* Selects li elements that are direct children of ul */
ul > li {
    list-style-type: square;
}

3. Adjacent Sibling Selector

/* Selects p that immediately follows h1 */
h1 + p {
    font-size: 18px;
    font-weight: bold;
}

/* Selects div that immediately follows img */
img + div {
    caption-side: bottom;
}

4. General Sibling Selector

/* Selects all p elements that follow h1 */
h1 ~ p {
    color: gray;
}

/* Selects all div elements that follow .intro */
.intro ~ div {
    margin-left: 20px;
}

5. Multiple Selectors

/* Applies styles to h1, h2, and h3 */
h1, h2, h3 {
    font-family: Arial, sans-serif;
    color: navy;
}

/* Applies styles to multiple classes */
.error, .warning, .alert {
    padding: 10px;
    border-radius: 5px;
}

Attribute Selectors

Attribute selectors allow you to select elements based on their attributes and attribute values.

Basic Attribute Selectors

/* Has attribute */
[title] {
    cursor: help;
}

/* Exact value */
[type="text"] {
    border: 1px solid gray;
}

/* Contains word */
[class~="featured"] {
    border: 2px solid gold;
}

/* Starts with */
[href^="https"] {
    color: green;
}

/* Ends with */
[href$=".pdf"] {
    background: url('pdf-icon.png') no-repeat right;
}

/* Contains substring */
[href*="google"] {
    color: blue;
}
graph TD A[Attribute Selectors] --> B["[attr]"] A --> C["[attr=value]"] A --> D["[attr~=value]"] A --> E["[attr^=value]"] A --> F["[attr$=value]"] A --> G["[attr*=value]"] B --> H[Has attribute] C --> I[Exact match] D --> J[Contains word] E --> K[Starts with] F --> L[Ends with] G --> M[Contains substring] style A fill:#f9f,stroke:#333,stroke-width:2px style B fill:#9cf,stroke:#333,stroke-width:2px style C fill:#fc9,stroke:#333,stroke-width:2px style E fill:#cf9,stroke:#333,stroke-width:2px style F fill:#c9f,stroke:#333,stroke-width:2px

Pseudo-classes

Pseudo-classes define special states of elements. They're like conditional selectors!

Common Pseudo-classes

/* Link states */
a:link { color: blue; }
a:visited { color: purple; }
a:hover { color: red; }
a:active { color: orange; }

/* Form states */
input:focus {
    outline: 2px solid blue;
}

input:disabled {
    opacity: 0.5;
}

input:checked {
    background-color: green;
}

/* Structural pseudo-classes */
li:first-child {
    font-weight: bold;
}

li:last-child {
    margin-bottom: 0;
}

li:nth-child(odd) {
    background-color: #f0f0f0;
}

li:nth-child(even) {
    background-color: #ffffff;
}

/* Content pseudo-classes */
p:empty {
    display: none;
}

div:not(.special) {
    color: gray;
}

Interactive Example

/* Button interaction states */
.button {
    background-color: blue;
    color: white;
    padding: 10px 20px;
    transition: all 0.3s ease;
}

.button:hover {
    background-color: darkblue;
    transform: translateY(-2px);
}

.button:active {
    transform: translateY(0);
}

.button:focus {
    outline: 3px solid lightblue;
}

Pseudo-elements

Pseudo-elements allow you to style specific parts of elements. They create "virtual" elements!

Common Pseudo-elements

/* First letter of paragraph */
p::first-letter {
    font-size: 2em;
    font-weight: bold;
    float: left;
}

/* First line of paragraph */
p::first-line {
    font-weight: bold;
    color: navy;
}

/* Before content */
.quote::before {
    content: """;
    font-size: 2em;
    color: gray;
}

/* After content */
.quote::after {
    content: """;
    font-size: 2em;
    color: gray;
}

/* Selection highlight */
::selection {
    background-color: yellow;
    color: black;
}

/* Placeholder text */
input::placeholder {
    color: #999;
    font-style: italic;
}

Selector Specificity

When multiple rules target the same element, specificity determines which styles apply. Think of it as a scoring system!

graph TD A[Specificity Hierarchy] --> B[Inline styles] A --> C[IDs] A --> D[Classes/Attributes/Pseudo-classes] A --> E[Elements/Pseudo-elements] A --> F[Universal selector] B --> G["1,0,0,0"] C --> H["0,1,0,0"] D --> I["0,0,1,0"] E --> J["0,0,0,1"] F --> K["0,0,0,0"] style B fill:#f99,stroke:#333,stroke-width:2px style C fill:#f96,stroke:#333,stroke-width:2px style D fill:#fc9,stroke:#333,stroke-width:2px style E fill:#ff9,stroke:#333,stroke-width:2px style F fill:#ffc,stroke:#333,stroke-width:2px

Specificity Examples

/* Specificity: 0,0,0,1 */
p { color: blue; }

/* Specificity: 0,0,1,0 */
.text { color: red; }

/* Specificity: 0,1,0,0 */
#content { color: green; }

/* Specificity: 0,0,1,1 */
p.text { color: orange; }

/* Specificity: 0,1,1,0 */
#content .text { color: purple; }

/* Inline style: 1,0,0,0 */
<p style="color: black;">Text</p>

The !important Exception

/* Overrides all other declarations */
p {
    color: red !important;
}

⚠️ Use sparingly! It breaks the natural cascade and makes CSS harder to maintain.

Cascade and Inheritance

The Cascade

CSS applies styles in order of:

  1. Origin (browser, user, author)
  2. Specificity
  3. Source order (last rule wins)

Inheritance

Some properties inherit from parent elements:

/* These properties inherit */
body {
    font-family: Arial, sans-serif;
    color: #333;
    line-height: 1.6;
}

/* Child elements inherit these values */
p {
    /* Inherits font-family, color, line-height */
}

/* Force inheritance */
.child {
    color: inherit;
    font-size: inherit;
}

/* Prevent inheritance */
.no-inherit {
    color: initial;
    all: unset; /* Resets all properties */
}

Best Practices

mindmap root((CSS Best Practices)) Naming Use meaningful names Follow naming conventions BEM methodology Organization Group related rules Order properties consistently Use comments for sections Specificity Avoid ID selectors Minimize nesting Avoid !important Performance Minimize selector complexity Group similar selectors Use shorthand properties

Example of Good Practices

/* Component: Card */
.card {
    /* Layout */
    display: flex;
    flex-direction: column;
    
    /* Box Model */
    margin: 1rem;
    padding: 1.5rem;
    
    /* Visual */
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.card__header {
    margin-bottom: 1rem;
}

.card__title {
    font-size: 1.5rem;
    font-weight: bold;
    color: #333;
}

.card__content {
    flex: 1;
    line-height: 1.6;
}

.card--featured {
    border: 2px solid gold;
}

Assignment: CSS Selectors

  1. Create an HTML file with:
    • Header with navigation menu
    • Main content with articles
    • Sidebar with links
    • Footer with contact info
  2. Create a CSS file that:
    • Uses at least 5 different selector types
    • Styles navigation links with hover states
    • Uses pseudo-classes for list items
    • Implements pseudo-elements for quotes
    • Demonstrates specificity rules
  3. Create a selector challenge page:
    • Target specific elements without modifying HTML
    • Style every nth item differently
    • Create hover effects using pseudo-classes
    • Use attribute selectors for links
  4. Validate your CSS using W3C CSS Validator

Bonus: Create a CSS selector cheat sheet with examples!