CSS - robbiehume/CS-Notes GitHub Wiki

Overview / tutorial links

Specific topic links

Look into:

  • Flex / grid
  • CSS nesting: link

web.dev tutorial notes (click here)

  • Say you have some HTML that you write some css for, but the content ends up wider than the 100px you specified and the content breaks out of your element. Why is that?
  • The box model is a core foundation of CSS. Understanding how the box model works, how it's affected by other aspects of CSS, and importantly, how you can control it, can help you write more predictable CSS
  • It's important to remember that everything displayed by CSS is a box, even if it's just some text, or has a border-radius that makes it look like a circle

Content and sizing

  • Good examples here
  • Boxes have different behavior based on their display value, their display dimensions, and the content they contain
  • You can control this using extrinsic sizing, or you can use intrinsic sizing to let the browser make decisions for you based on the content size
  • Overflow: happens when content is too big for the box it's in. You can manage how an element handles overflow content using the overflow property
  • Switching to intrinsic sizing lets the browser make decisions for you based on the box's content size. This makes overflow much less likely because the box resizes with its content

Areas of the box model

  • Good analogy: link Content Box: the area that the content lives in
  • The content can control the size of its parent, so this is usually the most variably sized area

Padding Box: surrounds the content box and is the space created by the padding property

  • Because padding is inside the box, the box's background is visible in the space it creates
  • If the box has overflow rules set, such as overflow: auto or overflow: scroll, the scrollbars also occupy this space

Border Box: surrounds the padding box

  • Its space is defined by the border value, which creates a visual frame for the element
  • The element's border edge is the limit of what you can see

Margin Box: the space around your box, defined by the box's margin rule

  • Properties such as outline and box-shadow occupy this space too because they're painted on top of the element and don't affect the size of the box
  • Changing your box's outline-width of 200px on a box doesn't change anything inside the border edge

General Notes

  • It's better to use a stylesheet than to do in-line styles (which should be avoided when possible)
  • Can use a star (*) as a wildcard
  • Can set based on role: div[role=main]
  • You need to add a dot (.) before class names, but not for HTML elements:
    .green {
      color: green;
    }
    p {
      color: green;
    }
  • Can use an element and class combo (.) and assign multiple to the style (,):
    • li.special,
      span.special.special2 {
        color: orange;
        font-weight: bold;
      }
    • This means "target any li element that has a class of special"
  • Descendant combinator (space): style based on location/hierarchy
    • li em {
        color: purple;
      }
    • This selector will select any <em> element that is inside (a descendant of) an <li>
  • Next-sibling combinator (+): style based on the element that came before it at same hierarchy level
    • h1 + p {
        font-size: 200%;
      }
    • This will style a paragraph when it comes directly after a heading at the same hierarchy level in the HTML
  • Styling based on id:
    • #my-id {
        color: red;
      }
  • Styling based on state:
    • Ex: change tag for a link based on the status(unvisitied, visited, hover)
      a:link {
        color: pink;
      }
      a:visited {
        color: green;
      }
      a:hover {
        text-decoration: none;
      }
  • Combining selectors and combinators:
    • It is worth noting that you can combine multiple selectors and combinators together. For example:
      /* selects any <span> that is inside a <p>, which is inside an <article>  */
      article p span { ... }
      /* selects any <p> inside an <h1> that has a class of "header"  */
      h1.header p { ... }
      /* selects any <p> that comes directly after a sibling <ul>, which comes directly after a sibling <h1>  */
      h1 + ul + p { ... }
  • Combining multiple types together:
    • body h1 + p .special {
        color: yellow;
        background-color: black;
        padding: 5px;
      }
    • This will style any element with a class of special, which is inside a <p>, which comes just after an <h1>, which is inside a <body>
  • Regex: link
    • [id^='td-']: selects anything that has an id that starts with td-
    • [id*='-input']: selects anything with -input- within it's id
    • [id$='0']: selects anything that has an id that ends in 0
    • Can combine them: div [id^='x'][id$='0'] selects any div that starts with x and ends with 0

Selectors: link1, link2

Cascade, specifity, and inheritance:

  • You may encounter scenarios where two selectors select the same HTML element
  • CSS has two rules to control which selector is stronger in the event of a conflict: cascade and specificity
  • Cascade: if two or more selectors are the same, then it will take the one that appears latest in the stylesheet
    • For example, with this stylesheet, the paragraph would be colored blue
      p { color: red; }
      p { color: blue; }
  • Specificity: if there's a conflict between two selectors, then the higher specificity one is used
    • Specificity overview
    • For example, a class selector is rated as being more specific than an element selector, so a paragraph with class of "special" will be red, not blue
      .special { color: red; }
      p { color: blue; }
  • Attribute selectors ([]): link
  • Pseudo-classes: link

Functions: link

  • While most values are relatively simple keywords or numeric values, there are some values that take the form of a function calc() function: do simple math within CSS
  • .box {
      width: calc(90% - 30px);
      background-color: green;
    }

Transform functions:

  • Some functions are rotate(), scale(), translate()

@rules:

  • Pronounced "at-rules", they provide instruction for what CSS should perform or how it should behave
  • A couple common ones are @import and @media

@media

  • The @media rule is used to apply styles conditionally based on the characteristics of the device or viewport displaying the content
  • This rule allows you to create responsive designs that adjust to different screen sizes, orientations, and other media features
  • Basic syntax: @media media-type and (media-feature) { ...
  • Example:
    • /* Styles for screens wider than 768px */
      @media screen and (min-width: 768px) { ...
      
      /* Styles for screens narrower than 600px */
      @media screen and (max-width: 600px) { ...
  • Can combine multiple criteria: @media screen and (max-width: 600px) and (orientation: portrait) // only if screen is narrower than 768 pixels and device is in portrait mode
  • Can also use a comma (,) as an or: @media screen and (max-width: 600px), screen and (orientation: landscape)
  • As well as not: @media not screen and (max-width: 600px)
  • Complex example:
    • /* Styles for screens between 600 and 900 pixels, or the device is in portrait orientation */
      @media (min-width: 600px) and (max-width: 900px), (orientation: portrait) {
        .sidebar {
          display: none;
        }
      }

Shorthands

  • Some properties like font, background, padding, border, and margin are called shorthand properties
  • Example:
    padding: 10px 15px 15px 5px; 
        --- is equal to ---
    padding-top: 10px; padding-right: 15px; padding-bottom: 15px; padding-left: 5px;

Floating elements (float)

  • Floating elements in CSS are elements that are removed from the normal document flow and positioned to the left or right within their containing element
  • This allows text and other inline elements to wrap around the floated element, creating a flexible and often visually appealing layout
  • It's done with the float property, though the use of floating has been somewhat diminished with the advent of more modern layout techniques like Flex and Grid

Pseudo elements and classes

Overview

  • Pseudo-Elements: used to style specific parts of an element's content or to insert new content (e.g., ::before, ::after, ::first-letter)
    • They typically use double colons (::), but are backwards compatible with single colons (:) as well
  • Pseudo-Classes: used to style elements based on their state or position (e.g., :hover, :focus, :nth-child). They use single colons (:)

Key differences:

  • Targeting: pseudo-elements target specific parts of an element's content (or create new content), while pseudo-classes target entire elements based on their state or position
  • Syntax: Pseudo-elements use double colons (::) in modern CSS, while pseudo-classes use single colons (:)
  • Functionality: Pseudo-elements are used to style or insert content that doesn’t exist in the HTML, while pseudo-classes apply styles based on conditions like user interactions or structural relationships

Pseudo elements (specifically ::before and ::after)

  • Pseudo-elements are used to style specific parts of an element's content. They don't actually exist in the HTML; they are created purely through CSS

::before and ::after

  • ::before and ::after overview (CSS-Tricks)
  • 7 practical uses for ::before and ::after
  • The ::before and ::after pseudo-elements in CSS are used to insert content before or after the content of an element
  • These pseudo-elements are powerful tools for adding stylistic elements to your web pages without needing additional HTML markup, keeping your HTML cleaner and more semantic
  • Content property:
    • To use ::before and ::after, you must define the content property. This property specifies what should be inserted before or after the content of the selected element
      • The content can be text, an empty string (for styling purposes), or even an image (using url())
    • Example:
      .example::before {
        content: 'Prefix ';
        color: red;
      }
  • Positioning:
  • The pseudo-elements are treated as inline elements by default, meaning they flow with the surrounding text. However, you can style them just like any other element, including setting their display property to block, inline-block, or other display types
  • You can also apply position properties (like absolute, relative, etc.) to control their placement relative to the parent element.

Pseudo classes (link)

  • Pseudo-classes are used to define a special state of an element. They target elements based on their state, position, or user interaction, rather than targeting a specific part of the element’s content
  • Examples:
    • :hover: Styles an element when the user hovers over it with a pointer
    • :focus: Styles an element when it has focus (e.g., a focused input field)
    • :nth-child(n): Selects elements based on their position in a parent’s list of children

Flexbox / grid

  • Note: Flexbox layout is most appropriate to the components of an application, and small-scale layouts, while the Grid layout is intended for larger scale layouts
  • Simple summary: flexbox is for alignment; grid is for layout
  • flexbox vs grid: summary; in-depth article
  • display:inline vs display:inline-block vs display:block in CSS (with visuals)
  • You can think of flex box as "one dimensional" and grid as "two dimensional"
    • While flexbox can make rows and columns in the sense that it allows elements to wrap, there’s no way to declaratively control where elements end up since the elements merely push along a single axis and then wrap or not wrap accordingly
    • You can (if you want to) declare the sizing of rows and columns and then explicitly place things into both rows and columns as we choose
  • Grid is mostly defined on the parent element. In flexbox, most of the layout (beyond the very basics) happen on the children
  • Grid is better at overlapping

Flexbox (flexible box layout):

Overview

  • Complete guide to flexbox: this is a great resource with visuals. Most of the notes in this wiki section are copied straight here
  • Flexbox aims at providing a more efficient way to lay out, align and distribute space among items in a container, even when their size is unknown and/or dynamic (thus the word “flex”)
  • The main idea behind the flex layout is to give the container the ability to alter its items’ width/height (and order) to best fill the available space (mostly to accommodate to all kind of display devices and screen sizes)
  • A flex container expands items to fill available free space or shrinks them to prevent overflow
  • Most importantly, the flexbox layout is direction-agnostic as opposed to the regular layouts: block which is vertically-based and inline which is horizontally-based

Basics and terminology

  • Since flexbox is a whole module and not a single property, it involves a lot of things including its whole set of properties
  • Some of them are meant to be set on the container (parent element, known as “flex container”) whereas the others are meant to be set on the children (said “flex items”)

Properties: Flex container

  • align-content: aligns a flex container's lines within when there is extra space in the cross-axis
    • This only takes effect on multi-line flexible containers, where flex-wrap is set to wrap or wrap-reverse Flex items
  • order: sets the order of the flex items. It doesn't affect the source order of the elements in the DOM, only the visual order on the screen
  • flex-basis: defines initial size of a flex item before any available space is distributed according to grow and shrink
    • Overrides the width or height properties (depending on flex-direction, unless flex-basis is set to auto (or not set)

Grid:

Overview

  • Complete guide to grid: this is a great resource with visuals. Most of the notes in this wiki are copied straight here
  • CSS Grid Layout (aka “Grid” or “CSS Grid”), is a two-dimensional grid-based layout system

Basics

  • To get started you have to define a container element as a grid with display: grid, set the column and row sizes with grid-template-columns and grid-template-rows, and then place its child elements into the grid with grid-column and grid-row
  • Similarly to flexbox, the source order of the grid items doesn’t matter. Your CSS can place them in any order, which makes it super easy to rearrange your grid with media queries
  • Imagine defining the layout of your entire page, and then completely rearranging it to accommodate a different screen width all with only a couple lines of CSS. Grid is one of the most powerful CSS modules ever introduced

Doing specific things

  • Replacing an image with the Kellum Method (may be outdated): link
    .hide-text {
      text-indent: 100%;
      white-space: nowrap;
      overflow: hidden;
    }
  • Have container element fill text content: (example
    • Set width and height to different combinations of min-content / max-content
    • To not have it go over a certain width/height, can also set a max-width and/or max-height
  • Vertically align text inside a flexbox
  • Horizontally align text in element: `text-align:' right, left, center, etc.
  • Center a div or text in a div: link
  • Extend clickable area of element: see example.css in repo
  • Render \n as newline: link
  • Bring element to front: set z-index: 2; or set it to higher than the other element that's on top of it

Specific attributes:

⚠️ **GitHub.com Fallback** ⚠️