How can I calculate a value from a number in a Webflow CMS collection, divide it by a fixed number, and use the resulting percentage as the width of a div for each item in the collection? Is there a way to do this without using CSS calc() or jQuery?

TL;DR
  • Bind a CMS Collection List to your desired collection and add a div inside each item for dynamic width with a class name for targeting.  
  • Use custom JavaScript to select divs, fetch numeric values, calculate percentages by dividing by a fixed number, and set div widths accordingly, ensuring data attributes are correctly set in CMS.

To dynamically set the width of a div based on a calculated percentage from a Webflow CMS collection, you need to use some custom code directly within Webflow. Unfortunately, Webflow does not natively support calculations directly in the designer, but you can achieve this by incorporating JavaScript. Here's how you can approach this:

1. Add the CMS Collection List

  • Drag and drop the CMS Collection List onto your canvas.
  • Bind the list to the desired CMS collection that contains the numeric field you want to use for calculations.

2. Set Up the Elements

  • Inside the Collection Item, add a div that will represent the dynamic width.
  • Assign a class name to this div so you can target it with custom JavaScript later.

3. Design for Consistency

  • Set a background color or any styling on the div to reflect visual changes.
  • Ensure each item within the Collection List has the same structure to support uniform functionality.

4. Use Custom JavaScript for Calculation

  • Open the Page Settings or use the Embed element to include custom JavaScript.
  • In the script, perform the following actions:
  • Select all the divs using the assigned class name.
  • Fetch the numeric value from each Collection Item.
  • Divide the value by your fixed number to get the percentage.
  • Set the width of the div based on the calculated percentage.

Example JavaScript:

document.addEventListener('DOMContentLoaded', function() {
  document.querySelectorAll('.percentage-div').forEach(function(div) {
    var numericValue = parseInt(div.getAttribute('data-value'));
    var fixedNumber = 100; // Your fixed number for calculation
    var percentageWidth = (numericValue / fixedNumber) * 100;
    div.style.width = percentageWidth + '%';
  });
});

5. Add Data Attributes

  • Ensure each div with the dynamic width has a data attribute like data-value containing the numerical field value. This can be done using CMS Collections to bind the data attribute with the value.

Summary

By using a combination of Webflow’s CMS Collections, custom divs for styling, and JavaScript for calculations, you can dynamically set the width of a div based on a percentage calculated from a CMS item’s numeric field. This approach does not require the use of CSS calc() or jQuery.

Rate this answer

Other Webflow Questions