CSS Cheatsheet
Tags: webdev, css, beginners, html
Published: 2024-03-13 11:53:55

CSS (Cascading Style Sheets) is the language used to style and format the appearance of your web pages.

## Selectors, Properties, and Values
CSS works by targeting specific elements in your HTML document and applying styles to them. This targeting is achieved through selectors.  Selectors point to the HTML elements you want to style.  Once you've selected the element, you define the styles using properties and values.

Here's an example to illustrate this:

```css
/* Selector */
p {
  /* Property: font-size */
  /* Value: 16px */
  font-size: 16px;
  
  /* Property: color */
  /* Value: blue */
  color: blue;
}
```
In this example:

The selector `p` targets all the paragraph elements (`<p>`) in our HTML document.
Inside the curly braces `{}`, we define two styles for the selected paragraphs.
The first property is `font-size`, which controls the size of the text. We set its value to `16px`.
The second property is `color`, which defines the text color. Here, we set the value to `blue`.

**Types of Selectors**
There are different ways to target elements with CSS selectors. Here are the most common ones:

- Tag Selector: This selects all elements of a specific HTML tag. For example, `h1` selects all heading elements (`<h1>`).
- Class Selector: This targets elements with a specific class attribute. We use a dot (`.`) followed by the class name. For example, `.important` selects all elements with the class "important".
- ID Selector: This targets a unique element using its ID attribute. We use a hash (`#`) followed by the ID. For example, `#banner` selects the element with the ID "banner".


```html
<h1>This is a heading</h1>  
<p class="important">This is important text.</p>  
<div id="footer">This is the footer.</div>
```

**Combining Selectors:** 
You can combine selectors to target elements more specifically.  For example, `h1.main` selects all `<h1>` elements with the class "main".


### Comments

Comments are lines of text ignored by the browser but help you understand and document your code.  Comments are added using `/*` and `*/` around the comment text.

```css
/* This is a comment explaining the styles for paragraphs */
p {
  font-size: 16px;
  color: blue;
}
```

## Common CSS Properties

This table summarizes some of the most commonly used CSS properties to control the look and feel of your webpages.

<table>
  <tr>
    <th>Category</th>
    <th>Property</th>
    <th>Description</th>
  </tr>
  <tr>
  <td rowspan="6">Text Formatting</td>
  <td>font-family</td>
  <td>Defines the font family for text.</td>
</tr>
<tr>
  <td>font-size</td>
  <td>Specifies the size of the font.</td>
</tr>
<tr>
  <td>font-weight</td>
  <td>Sets the thickness of the font.</td>
</tr>
<tr>
  <td>color</td>
  <td>Sets the color of the text.</td>
</tr>
<tr>
  <td>text-align</td>
  <td>Aligns the text within its container.</td>
</tr>
<tr>
  <td>text-decoration</td>
  <td>Adds decorations to text (e.g., underline, line-through).</td>
</tr>
<tr>
  <td colspan="3">
     <pre><code>
.selector {
  font-family: Arial, sans-serif;
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  text-decoration: underline;
}
    </code></pre>
  </td>
</tr>
  <tr>
  <td rowspan="4">Background</td>
  <td>background-color</td>
  <td>Sets the background color of an element.</td>
</tr>
<tr>
  <td>background-image</td>
  <td>Specifies an image to use as the background.</td>
</tr>
<tr>
  <td>background-position</td>
  <td>Specifies the starting position of a background image.</td>
</tr>
<tr>
  <td>background-repeat</td>
  <td>Controls how background images are repeated.</td>
</tr>
<tr>
  <td colspan="3">
    <pre><code>
/* Background example */
.selector {
  background-color: #ffffff; /* Sets the background color */
  background-image: url('background.jpg'); /* Sets the background image */
  background-position: center top; /* Sets the position of the background image */
  background-repeat: no-repeat; /* Prevents background image from repeating */
}
    </code></pre>
  </td>
</tr>

 <tr>
  <td rowspan="5">Borders & Margins</td>
  <td>border-style</td>
  <td>Sets the style of the border.</td>
</tr>
<tr>
  <td>border-width</td>
  <td>Sets the width of the border.</td>
</tr>
<tr>
  <td>border-color</td>
  <td>Sets the color of the border.</td>
</tr>
<tr>
  <td>margin</td>
  <td>Specifies the outside margin of an element.</td>
</tr>
<tr>
  <td>padding</td>
  <td>Specifies the inner padding of an element.</td>
</tr>
<tr>
  <td colspan="3">
    <pre><code>
/* Borders & Margins example */
.selector {
  border-style: solid; /* Sets the style of the border */
  border-width: 2px; /* Sets the width of the border */
  border-color: #000000; /* Sets the color of the border */
  margin: 20px; /* Sets the outside margin */
  padding: 10px; /* Sets the inner padding */
}
    </code></pre>
  </td>
</tr>

 <tr>
  <td rowspan="4">Dimensions & Positioning</td>
  <td>width</td>
  <td>Sets the width of an element.</td>
</tr>
<tr>
  <td>height</td>
  <td>Sets the height of an element.</td>
</tr>
<tr>
  <td>display</td>
  <td>Specifies the type of box an element generates.</td>
</tr>
<tr>
  <td>position</td>
  <td>Sets the positioning method of an element.</td>
</tr>
<tr>
  <td colspan="3">
    <pre><code>
/* Dimensions & Positioning example */
.selector {
  width: 200px; /* Sets the width */
  height: 100px; /* Sets the height */
  display: block; /* Specifies the display type */
  position: relative; /* Sets the positioning method */
}
    </code></pre>
  </td>
</tr>

</table>

## Flexbox & Grid
 
Flexbox and Grid are two powerful layout methods in CSS that offer more control over how you arrange elements on your webpage. Here's a quick cheatsheet to get you started:

### Flexbox

Flexbox allows you to distribute space evenly or unevenly between elements within a container. It's ideal for one-dimensional layouts like navigation bars or image galleries.

**Key Concepts**

**Flex Container**: The parent element that holds the flex items. Set display: flex; on this element.
**Flex Items:** The child elements within the flex container.

**Properties:**

`flex-direction`: (row, column, row-reverse, column-reverse) Defines the main axis (direction) along which flex items are laid out.
`justify-content`: (flex-start, flex-end, center, space-between, space-around) Controls how flex items are distributed along the main axis.
`align-items`: (flex-start, flex-end, center, baseline, stretch) Aligns flex items perpendicular to the main axis.
`align-self`: (stretch, flex-start, flex-end, center, baseline) Overrides align-items for individual flex items.
`flex-grow`: (number) Sets the flex grow factor for an item, determining how much extra space it can occupy.
`flex-shrink`: (number) Sets the flex shrink factor for an item, determining how much it can shrink if there's not enough space.

Example:

```css
/* Style for the navigation container */
.navigation {
  display: flex; /* Display items in a flex container */
  justify-content: space-between; /* Align items along the main axis with space between */
  align-items: center; /* Align items at the center of the cross axis */
}

/* Style for navigation links */
.navigation a {
  padding: 10px; /* Add padding around the links */
  text-decoration: none; /* Remove underline from links */
}
```

### Grid

Grid allows you to create a grid-based layout system, defining rows and columns for more complex layouts.

**Key Concepts**

**Grid Container:** The parent element that holds the grid items. Set display: grid; on this element.
**Grid Items:** The child elements positioned within the grid cells.

**Properties:**
`grid-template-columns`: Defines the layout of columns in the grid (e.g., "1fr 2fr" - two columns, first one takes 1 unit of space, second takes 2).
`grid-template-rows`: Defines the layout of rows in the grid (e.g., `auto 100px` - first row has automatic height, second is 100px).
`grid-gap`: Sets the spacing between grid items (e.g., `10px`).
`grid-column-start/grid-row-start`: Positions an item by specifying the starting cell (e.g., `grid-column-start: 2` - starts at the second column).
`grid-column-end/grid-row-end`: Positions an item by specifying the ending cell (e.g., `grid-row-end: span 2` - spans two rows).

Example:

```css
/* Style for the grid container */
.grid-container {
  display: grid; /* Use CSS Grid layout */
  /* Create responsive columns:
     - auto-fit: Adjusts the number of columns to fit the container width
     - minmax(200px, 1fr): Each column has a minimum width of 200px and expands to fill available space */
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  grid-gap: 10px; /* 10 pixels of gap between grid items */
}

```

## Pseudo-Classes
Pseudo-classes are special keywords that can be added to selectors to style elements based on their state or position in the document tree.

**Examples:**
`:hover`: Styles an element when the user hovers over it.

```css
button:hover {
  background-color: #f0f0f0;
}
```
`:focus`: Styles an element when it receives focus.

```css
input:focus {
  border-color: blue;
}
```
`:nth-child()`: Styles elements based on their position within a parent.

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

## Pseudo-Elements:
Pseudo-elements allow you to style certain parts of an element. They are denoted by double colons :: in CSS.

**Examples:**
`::before`: Inserts content before the selected element.

```css
.quote::before {
  content: '"';
}
```
`::after`: Inserts content after the selected element.

```css
.tooltip::after {
  content: 'ℹ️';
}
```
`::first-line`: Styles the first line of a block-level element.

```css
p::first-line {
  font-weight: bold;
}
```
**Combined Example:**

```css
/* Style links */
a {
  color: blue;
}

/* Change link color on hover */
a:hover {
  color: red;
}

/* Add quotation marks before blockquote content */
blockquote::before {
  content: '"';
}

/* Style the first line of paragraphs */
p::first-line {
  font-weight: bold;
}
```
**Combined Example:**

```css
/* Style links */
a {
  color: blue;
}

/* Change link color on hover */
a:hover {
  color: red;
}

/* Add quotation marks before blockquote content */
blockquote::before {
  content: '"';
}

/* Style the first line of paragraphs */
p::first-line {
  font-weight: bold;
}
```

## Measurements 

In CSS, you use units to define the size or position of elements. **Here's a breakdown of some common units:**

**px (pixels):** The most basic unit, representing a single pixel on your screen. It's fixed and device-independent.
**em (ems):** Relative unit based on the font size of the parent element. For example, `2em` would be twice the font size of the parent.
**rem (root ems):** Relative unit based on the font size of the root element (usually `<html>`). This ensures consistent sizing across the entire document, even when nested elements have different font sizes.
**% (percentage):** Relative unit based on a percentage of its containing element's width or height. Useful for responsive design and creating layouts that scale with different screen sizes.
**vh (viewport height):** Represents a percentage of the viewport's height. Great for defining element heights relative to the user's screen.
**vw (viewport width): **Represents a percentage of the viewport's width. Useful for defining element widths relative to the user's screen.

**Choosing the Right Unit:**

**px:** Use for specific, fixed sizes that shouldn't change with font size or screen size (e.g., icon sizes, borders).
**em:** Use for relative sizing within a specific element context (e.g., slightly larger font for headings within a section).
**rem:** Use for consistent, scalable sizing across your entire layout (e.g., setting base font sizes, margins, paddings).
**%:** Use for creating responsive layouts, where elements should adjust based on the screen size (e.g., setting container widths, margins as percentages).
**vh/vw:** Use for elements that should scale proportionally with the viewport size (e.g., creating a full-height background image).

```css
/* Using px */
.icon {
  width: 32px; /* Fixed size for icon */
  height: 32px; /* Fixed size for icon */
  border: 1px solid #000; /* Border with a fixed width of 1px */
}

/* Using em */
.section-heading {
  font-size: 1.5em; /* Font size relative to the parent element */
}

/* Using rem */
body {
  font-size: 16px; /* Base font size */
}

.container {
  padding: 1rem; /* Padding that scales based on the base font size */
}

/* Using % */
.container {
  width: 80%; /* Container width as a percentage of the parent element */
  margin: 0 auto; /* Center the container horizontally */
}

/* Using vh/vw */
.full-height-bg {
  height: 100vh; /* Full height of the viewport */
}

.full-width-bg {
  width: 100vw; /* Full width of the viewport */
}
```
`px` is used for fixed sizes like icon dimensions and border widths.
`em` is used for relative sizing within a specific element context, such as headings within a section.
`rem` is used for consistent, scalable sizing across the entire layout, like setting base font sizes and paddings.
`%` is used for creating responsive layouts, where elements adjust based on screen size, such as container widths and margins.
`vh` and `vw` are used for elements that should scale proportionally with the viewport size, such as background images that need to cover the entire viewport.

## Selector Types
CSS selectors are the backbone of styling your web pages. They target specific elements or groups of elements to apply styles. Here's a breakdown of common selector types:

**Basic Selectors:**

**Element Selector** (e.g., `h1, p, div`): Targets specific HTML elements by their tag name.
**ID Selector** (e.g., `#uniqueID`): Targets an element with a unique ID attribute. IDs should only be used once per page.
**Class Selector** (e.g., `.className`): Targets elements with a specific class name attribute. Classes can be applied to multiple elements.

**Combinators:**

**Descendant Combinator** (>): Targets elements that are direct children of another element. (e.g., #title > p selects paragraphs that are direct children of the element with ID "title")

```css
/* Selects paragraphs that are direct children of the element with ID "title" */
#title > p {
  color: blue;
}
```

**Child Combinator** (` `) Targets elements that are any child (direct or indirect) of another element.

```css
/* Selects any paragraph that is a child (direct or indirect) of the element with class "content" */
.content p {
  font-weight: bold;
}
```

**Adjacent Sibling Combinator** (`+`): Targets the element immediately following another element, on the same level in the HTML structure. (e.g., `h1 + p` selects paragraphs that directly follow an `h1` heading)

```css
/* Selects paragraphs that directly follow an h1 heading */
h1 + p {
  margin-top: 20px;
}
```

**General Sibling Combinator** (`~`): Targets any sibling element (direct or indirect) following another element, on the same level in the HTML structure. (e.g., `h1 ~ p` selects all paragraphs that are siblings of an h1 heading, not necessarily immediately following)

```css
/* Selects all paragraphs that are siblings of an h1 heading, not necessarily immediately following */
h1 ~ p {
  color: green;
}
```

**Attribute Selectors:**

**Attribute Existence** (e.g., `[attr]`): Targets elements that have a specific attribute, regardless of its value. (e.g., `[href]` selects elements with an `href `attribute)

```css
/* Selects elements with a "href" attribute */
[href] {
  color: blue;
}
```
**Attribute Value** (e.g., `[attr="value"]`): Targets elements that have a specific attribute with a specific value. (e.g., `[href="#top"]` selects elements with an href attribute that links to "#top")

```css
/* Selects elements with an href attribute that links to "#top" */
[href="#top"] {
  font-weight: bold;
}
```

**Attribute Contains** (e.g., `[attr*="value"]`): Targets elements that have an attribute whose value contains a specific substring. (e.g., `[class*="button"]` selects elements with class names containing "button")

```css
/* Selects elements with class names containing "button" */
[class*="button"] {
  background-color: yellow;
}
```

**Grouping Selectors:**
Use commas (`,`) to target multiple selectors of the same type in one rule.
Example: `h1, h2, h3 { color: blue; }` (sets blue color for all headings h1, h2, and h3)

## Animation in CSS
CSS animations allow you to create dynamic and engaging effects on web pages. They are achieved by gradually changing the style of an element over a specified duration.

**Keyframes:**
Keyframes define the stages and styles of an animation. They specify what happens at certain points during the animation sequence.

```css
@keyframes slide-in {
  0% {
    transform: translateX(-100%);
  }
  100% {
    transform: translateX(0);
  }
}
```

**Animation Property:**
The animation property is used to apply an animation to an element. It includes values for animation name, duration, timing function, delay, iteration count, direction, fill mode, and play state.

```css
.element {
  animation: slide-in 1s ease-in-out 0s 1 normal forwards;
}
```
**In this example:**
`slide-in`: Name of the animation defined in keyframes.
`1s`: Duration of the animation (1 second).
`ease-in-out`: Timing function (acceleration and deceleration).
`0s`: Delay before starting the animation.
`1`: Number of iterations (1 time).
`normal`: Direction of the animation (forward).
`forwards`: Fill mode (keeps the end styles of the animation).

**Animation Properties:**
`animation-name`: Specifies the name of the keyframe animation.
`animation-duration`: Duration of the animation.
`animation-timing-function`: Timing function for the animation (e.g., ease, linear, ease-in-out).
`animation-delay`: Delay before starting the animation.
`animation-iteration-count`: Number of times the animation should repeat.
`animation-direction`: Specifies whether the animation should play forwards, backwards, or alternate.
`animation-fill-mode`: Defines how the styles are applied before and after the animation.
`animation-play-state`: Defines whether the animation is running or paused.

```css
@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
}

.element {
  animation: pulse 2s infinite alternate;
}
```

This example creates a pulse animation that scales the element to `1.2` times its original size and back to its original size continuously.

## Transitions in CSS
CSS transitions allow you to smoothly change property values over a specified duration. They provide a simple way to add subtle animations to your web elements.

**Transition Property:**
The transition property is used to define the transition effect for a specified CSS property. It includes values for property, duration, timing function, and delay.

```css
.element {
  transition: property duration timing-function delay;
}
```
`property`: Specifies the CSS property to which the transition applies.
`duration`: Duration of the transition effect (e.g., `0.5s, 1s`).
`timing-function`: Timing function for the transition (e.g., `ease, linear, ease-in-out`).
`delay`: Delay before starting the transition (optional).

```css
.button {
  background-color: #007bff;
  color: #fff;
  transition: background-color 0.3s ease-in-out;
}

.button:hover {
  background-color: #0056b3;
}
```

In this example, when hovering over the button, the background color smoothly transitions from `#007bff` to `#0056b3` over a duration of `0.3s` with an ease-in-out timing function.

**Transition Properties:**
`transition-property`: Specifies the CSS property to which the transition applies (e.g., all, color, opacity).
`transition-duration`: Duration of the transition effect.
`transition-timing-function`: Timing function for the transition.
`transition-delay`: Delay before starting the transition.

```css
.element {
  transition: background-color 0.3s ease-in-out, color 0.3s ease-in-out;
}
```
in this example:

`.element`: This is a class selector that targets HTML elements with the class "element".

`transition`: This property specifies the transition effect for the specified CSS properties. It's a shorthand property that combines `transition-property`, `transition-duration`, `transition-timing-function`, and `transition-delay`.

`background-color 0.3s ease-in-out, color 0.3s ease-in-out`: This specifies two transition effects:

**Transition for background-color**: The background color will transition over a duration of `0.3s` with an `ease-in-out` timing function. This means that the transition will start slowly, speed up in the middle, and then slow down again at the end.

**Transition for color**: The text color will also transition over the same duration and timing function as the background color.

**More info **
[Css transition](https://developer.mozilla.org/en-US/docs/Web/CSS/transition)
[CSS Sizing and Positioning Properties](https://spacema-dev.com/understanding-css-sizing-and-positioning-properties-a-guide-to-object-fit-and-related-properties/)
[Css position property](https://www.w3schools.com/css/css_positioning.asp)