How to avoid CSS ch layout shifts
Tags: css, webdev
Published: 2023-08-31 15:43:38

**Written by [Pascal Akunne](https://blog.logrocket.com/author/pascalakunne/)✏️**

CSS layout shifts refer to the unexpected movement (or shifting) of elements within the layout of a webpage during the rendering process. This occurs when the dimensions or positions of elements change, causing content to reflow or shift on the page. Layout shifts can lead to poor UX, as the movement may disrupt user interaction or make the content difficult to read or access.

In this article, we’ll investigate layout shifts that occur when using the CSS `ch` unit to size elements. We’ll explore why these shifts occur, consider strategies for avoiding them, and discuss best practices for working with CSS units to help provide a better user experience.

_Jump ahead:_

*   [What causes CSS layout shifts?](#what-causes-css-layout-shifts)
*   [Understanding the CSS `ch` unit](#understanding-css-ch-unit)
*   [Alternatives to using the CSS `ch` unit](#alternatives-css-ch-unit)
    *   [Using fixed-width containers](#using-fixed-width-containers)
    *   [Limiting dynamic content](#limiting-dynamic-content)
    *   [Using padding or margins](#using-padding-margins)
    *   [Testing and modifying the layout](#testing-modifying-layout)
    *   [Exploring alternative units](#exploring-alternative-units)
    *   [Using CSS Flexbox or CSS Grid](#using-flexbox-css-grid)
    *   [Implementing responsive design principles](#implementing-responsive-design-principles)
    *   [Replacing `ch` with `rem`](#replacing-ch-with-rem)
*   [Best practices for working with CSS units](#best-practices-working-css-units)

## What causes CSS layout shifts?

CSS layout shifts can occur due to various factors, such as:

*   **Dynamic content:** If the size or position of dynamic content inside a layout is altered as a result of user interaction, data updates, or other circumstances, it may result in unanticipated layout alterations
*   **Content loading:** When resources like as photos, videos, or external scripts are loaded asynchronously or slowly, the content may not initially occupy its intended space, creating a shift when it eventually appears
*   **CSS animations or transitions**: Transitions or animations can alter the positions or dimensions of elements, potentially resulting in layout shifts
*   **Font loading:** If the fonts used in a webpage are not immediately accessible, the browser may render the information with fallback fonts first, and then a shift may occur when the required fonts are loaded

## Understanding the CSS `ch` unit <a name="understanding-css-ch-unit">

The CSS `ch` unit is a relative length unit that represents the width of the "0" (zero) character in the chosen font. It is primarily used to create responsive designs that scale with the font size.

The `ch` unit allows us to define element widths or spacing relative to the width of the "0" character, which is typically a monospaced character, meaning it occupies the same amount of space as other characters in the font.

In monospace, or fixed-width, fonts like Courier, where all characters are the same width, the `ch` unit works as an exact measurement. That is, `1ch` equals one character. In proportional, or variable-width, fonts like Georgia, any given character could be wider or narrower than the “0” character.

Consider the following example:

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    .box1 {
      width: 25ch;
      padding: 3ch;
      font-family: Georgia, Arial, sans-serif;
      font-size: 16px;
      border: 1px solid black;
    }
    .box2 {
      width: 25ch;
      padding: 3ch;
      font-family: Courier, Arial, sans-serif;
      font-size: 16px;
      border: 1px solid black;
    }
  </style>
  <title>Document</title>
</head>
<body>
  <div class="box1">
    - Box 1 has a width of 25ch and padding of 3ch, with Georgia as the font family.
    <br> - Write some 20-character word: abcdefghijklmopqrst iiiiiiiiiiiiiiiiiiii mmmmmmmmmmmmmmmmmmmm
  </div>
  <br>
  <div class="box2">
    - Box 2 has a width of 25ch and padding of 3ch, with Courier as the font family.
    <br>- Write some 20-character words: abcdefghijklmopqrst iiiiiiiiiiiiiiiiiiii mmmmmmmmmmmmmmmmmmmm
  </div>
</body>
</html>
```

Here’s the output from this code:

![Output Example CSS Ch Unit](http://blog.logrocket.com/wp-content/uploads/2023/08/output-example-css-ch-unit.png)

If you set the width of an element to `25ch`, it will be approximately 25 times the width of the "0" character in the current font. When you change the font size, the element's width will adjust proportionally.

In the above example, Box 1 uses the Georgia proportional font, which causes the “m” character to extend past the box. Box 2 uses the Courier monospace font, which results in the box scaling proportionally.

The `ch` unit is determined by the width of the "0" character in the font of choice. It is meant to serve as a relative unit of measurement that scales with font size. It is not intended to reference graphics or non-textual items, the dimensions of which are often not defined by character widths.

Other CSS units, such as pixels (`px`), percentages (`%`), or viewport-based units (`vw`, `vh`, `vmin`, `vmax`), are commonly used to determine the size and position of photos or other non-textual elements on a webpage.

## Alternatives to using the CSS `ch` unit <a name="alternatives-css-ch-unit">

There are several strategies you can use to avoid CSS layout shifts associated with the `ch` unit. Let’s take a look.

### Using fixed-width containers <a name="using-fixed-width-containers">

By using fixed-width containers that specify width in pixels or percentages, you can ensure that the container's width remains constant.

### Limiting dynamic content <a name="limiting-dynamic-content">

Implement methods, such as establishing character limitations or timing long content, to minimize or regulate the differences in a layout's dynamic content.

### Using padding or margins <a name="using-padding-margins">

Instead of using `ch` to directly size components, utilize padding or margins to provide space and give flexibility for content modifications. This allows the content to change without affecting the overall layout.

### Testing and modifying the layout <a name="testing-modifying-layout">

To identify possible layout shifts, test your layout on a regular basis with varying fonts and content lengths; be sure to make any required changes to maintain stability and consistency across multiple scenarios.

### Exploring alternative units <a name="exploring-alternative-units">

Consider using more predictable and consistent CSS units such as pixels, percentages, or viewport-based units; these units are less reliant on font attributes and provide greater control over layout consistency.

### Using CSS Flexbox or CSS Grid <a name="using-flexbox-css-grid">

These layout systems can be used to develop flexible and responsive designs. [CSS Flexbox](https://blog.logrocket.com/css-flexbox-vs-css-grid/#what-flexbox) and [CSS Grid](https://blog.logrocket.com/css-grid-guide/) may be helpful in reducing layout shifts by allowing for flexible resizing and alignment without relying largely on `ch` unit sizing.

### Implementing responsive design principles <a name="implementing-responsive-design-principles">

Responsive design strategies, like media queries and fluid designs, can help ensure your layout adjusts effortlessly to multiple screen sizes and devices by developing with a mobile-first approach and utilizing relative units.

### Replacing `ch` with `rem` <a name="replacing-ch-with-rem">

Another strategy for avoiding layout shifts and maintaining more consistent layouts is to replace the `ch` unit with the relative root em (`rem`) unit. Here are some examples of how using `rem` may be beneficial:

*   **Scalability:** The `rem` unit is ideal for developing flexible and responsive designs. You can simply scale the entire layout appropriately by altering the root font size with media queries or CSS preprocessors, maintaining consistent spacing and scaling across various devices and screen sizes
*   **Consistent sizing:** Unlike the `ch` unit, which is determined by the width of a given character, the `rem` unit is determined by the font size of the root element. Setting a base font size at the root level of your CSS (often in the `<html>` element) makes all additional element sizes defined with 'rem' relative to this base size. This maintains constant size across all parts, irrespective of the font chosen
*   **Accessibility:** Using the `rem` unit can improve accessibility by allowing users to change the font size in their browser settings without disrupting the layout. As the relative sizing adjusts to the user's desired font size, the layout remains steady
*   **Predictability:** Because it is unaffected by differences in the size of individual characters in various fonts, the `rem` unit is more predictable than the `ch` unit. Elements scaled with the `rem` unit will keep their relative proportions for as long as the root font size stays stable, resulting in more dependable layouts

To replace the `ch` unit with `rem`, follow these steps:

First, set a base font size in the root element of your CSS:

```css
html {
  font-size: 20px; /* Base font size */
}
```

Next, define your element sizes using `rem` units:

```css
.container {
  width: 24rem;
  padding: 1rem;
}
```

By using `rem` units consistently throughout your layout, you can achieve more reliable and adaptable designs that avoid the layout shifts associated with the `ch` unit.

## Best practices for working with CSS units <a name="best-practices-working-css-units">

For improved user experience, follow these best practices when using CSS units:

*   **Use relative units for responsiveness:** Relative units, like percentages, viewport-based units, and relative `em` or `rem` units, are ideal for designing responsive designs; they scale appropriately to the parent or viewport size, enabling you to adjust your layout to multiple devices and screen sizes
*   **Use pixels for fixed sizes:** Pixels are absolute units of measurement that allow for exact control over element sizes. They are appropriate for establishing fixed-width components or when pixel-perfect layouts are required. However, be cautious when using pixels for font sizes, as this could limit accessibility as users scale their content
*   **Use percentages for fluid layouts:** Percentages are great for generating fluid layouts that change depending on parent containers; they are typically used for values like width, height, padding, margin, and positioning. You can develop flexible designs that adapt to shifts in screen size or parent element dimension by carefully employing percentages
*   **Use viewport units for responsive layouts:** Viewport-based units are proportional to viewport dimensions. They can be used to create responsive typography, resize items based on viewport width or height, or achieve full-screen layouts. For the best user experience, avoid high aspect ratios and irregular scaling across multiple devices
*   **Use `em` and `rem` for scalable typography:** `em` units are positioned relative to their parent element, whereas `rem` units are positioned relative to the root element. They offer adaptable and accessible typography that changes proportionately to the user's font size preferences
*   **Use CSS Flexbox and CSS Grid for flexibility:** CSS Flexbox and Grid layouts are extremely useful for developing flexible and responsive designs. They provide you with more flexibility over element sizing, alignment, and position, decreasing your dependency on specific units. You can make use of these layout methods to build dynamic and adaptive designs for a variety of screen sizes
*   **Test and optimize for different scenarios:** To guarantee that your layout remains visually appealing and functional, test it across a variety of devices, browsers, and screen sizes. Pay attention to font settings because they could affect scaling units like `ch` or `rem`. Refine your design for uniformity and usability across multiple scenarios

## Conclusion

Avoiding CSS layout shifts is critical for providing a consistent user experience. You may minimize layout shifts and preserve consistency by using fixed-width containers, restricting dynamic content variations, and utilizing responsive design solutions with relative units, such as percentages or viewport-based units. Remember to test and optimize your layouts across several devices and font settings to guarantee stability and a visually appealing user experience.