Intro to CSS

Including CSS

  1. Inline CSS <element style="property: value;">
  2. Internal CSS using <style> tag
    <style>
    /* CSS rules go here */
    .highlight { background-color: yellow; }
    </style>
  3. External CSS using <link> tag
    <link rel="stylesheet" href="styles.css">

Basic Syntax + Comments

/* CSS Comment */
selector {
  property: value;
}

Selectors

Tag Name Selector

Applies to all elements of a certain type, e.g., p { color: blue; }

Class Selector

Applies to all elements with a certain class, e.g., .highlight { background-color: yellow; }

This is highlighted text.

ID Selector

Applies to the single element with a certain ID, e.g., #important { color: red; }

This is important text.

Combining Selectors

Sharing Selectors with Comma

Applies same styles to multiple selectors, e.g., h2, h3 { color: darkblue; }

Descendant Selector

Targets elements inside other elements, e.g., section ul li { margin-bottom: 10px; }

Direct Child Selector

Targets direct children of an element, e.g., .container > p { margin: 10px 0; }

This paragraph is directly inside a container.

Adjacent Sibling Selector

Targets the next sibling, e.g., #adjacent-sibling + p { color: green; }

This paragraph is an adjacent sibling.

Subsequent Sibling Selector

Targets all subsequent siblings, e.g., #subsequent-example ~ p { font-style: italic; }

This paragraph is a subsequent sibling.

Another subsequent sibling paragraph.

Examples

Styling labels based on the checkbox value. This uses the adjacent sibling selector.

input:checked + label {
  color: green;
  font-weight: bold;
}
    

Displaying error messages when a form input is invalid. This uses the subsequent sibling selector.

Your form has errors!

Please enter a valid email address.

.error {
  display: none;
}

input:invalid ~ .error {
  display: block;
  color: red;
}