DEV Community

Cover image for CSS Cheatsheet
Mike Varenek
Mike Varenek

Posted on

CSS Cheatsheet

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:

/* Selector */
p {
  /* Property: font-size */
  /* Value: 16px */
  font-size: 16px;

  /* Property: color */
  /* Value: blue */
  color: blue;
}
Enter fullscreen mode Exit fullscreen mode

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".
<h1>This is a heading</h1>  
<p class="important">This is important text.</p>  
<div id="footer">This is the footer.</div>
Enter fullscreen mode Exit fullscreen mode

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.

/* This is a comment explaining the styles for paragraphs */
p {
  font-size: 16px;
  color: blue;
}
Enter fullscreen mode Exit fullscreen mode

Common CSS Properties

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

Category Property Description
Text Formatting font-family Defines the font family for text.
font-size Specifies the size of the font.
font-weight Sets the thickness of the font.
color Sets the color of the text.
text-align Aligns the text within its container.
text-decoration Adds decorations to text (e.g., underline, line-through).

.selector {
  font-family: Arial, sans-serif;
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  text-decoration: underline;
}
    
Background background-color Sets the background color of an element.
background-image Specifies an image to use as the background.
background-position Specifies the starting position of a background image.
background-repeat Controls how background images are repeated.

/* 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 */
}
    
Borders & Margins border-style Sets the style of the border.
border-width Sets the width of the border.
border-color Sets the color of the border.
margin Specifies the outside margin of an element.
padding Specifies the inner padding of an element.

/* 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 */
}
    
Dimensions & Positioning width Sets the width of an element.
height Sets the height of an element.
display Specifies the type of box an element generates.
position Sets the positioning method of an element.

/* 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 */
}
    

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:

/* 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 */
}
Enter fullscreen mode Exit fullscreen mode

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:

/* 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 */
}

Enter fullscreen mode Exit fullscreen mode

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.

button:hover {
  background-color: #f0f0f0;
}
Enter fullscreen mode Exit fullscreen mode

:focus: Styles an element when it receives focus.

input:focus {
  border-color: blue;
}
Enter fullscreen mode Exit fullscreen mode

:nth-child(): Styles elements based on their position within a parent.

li:nth-child(odd) {
  background-color: #f0f0f0;
}
Enter fullscreen mode Exit fullscreen mode

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.

.quote::before {
  content: '"';
}
Enter fullscreen mode Exit fullscreen mode

::after: Inserts content after the selected element.

.tooltip::after {
  content: 'ℹī¸';
}
Enter fullscreen mode Exit fullscreen mode

::first-line: Styles the first line of a block-level element.

p::first-line {
  font-weight: bold;
}
Enter fullscreen mode Exit fullscreen mode

Combined Example:

/* 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;
}
Enter fullscreen mode Exit fullscreen mode

Combined Example:

/* 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;
}
Enter fullscreen mode Exit fullscreen mode

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).

/* 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 */
}
Enter fullscreen mode Exit fullscreen mode

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")

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

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

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

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)

/* Selects paragraphs that directly follow an h1 heading */
h1 + p {
  margin-top: 20px;
}
Enter fullscreen mode Exit fullscreen mode

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)

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

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 hrefattribute)

/* Selects elements with a "href" attribute */
[href] {
  color: blue;
}
Enter fullscreen mode Exit fullscreen mode

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")

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

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")

/* Selects elements with class names containing "button" */
[class*="button"] {
  background-color: yellow;
}
Enter fullscreen mode Exit fullscreen mode

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.

@keyframes slide-in {
  0% {
    transform: translateX(-100%);
  }
  100% {
    transform: translateX(0);
  }
}
Enter fullscreen mode Exit fullscreen mode

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.

.element {
  animation: slide-in 1s ease-in-out 0s 1 normal forwards;
}
Enter fullscreen mode Exit fullscreen mode

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.

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

.element {
  animation: pulse 2s infinite alternate;
}
Enter fullscreen mode Exit fullscreen mode

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.

.element {
  transition: property duration timing-function delay;
}
Enter fullscreen mode Exit fullscreen mode

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).

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

.button:hover {
  background-color: #0056b3;
}
Enter fullscreen mode Exit fullscreen mode

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.

.element {
  transition: background-color 0.3s ease-in-out, color 0.3s ease-in-out;
}
Enter fullscreen mode Exit fullscreen mode

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
CSS Sizing and Positioning Properties
Css position property

Top comments (2)

Collapse
 
ademagic profile image
Miko

Love a good cheatsheet. Interesting format having it on dev.to as well.
How often do you use this?

Collapse
 
get_pieces profile image
Pieces 🌟

Useful cheatsheet!! đŸ”Ĩ