I am really struggling to comprehend this CSS calc() calculation - it's really giving me a headache

Struggling to grasp a CSS calculation that evenly spaces children in a flexed container with a defined gap between them? You're not alone!

I'm looking to streamline this process by creating a SASS(SCSS) function for the calculation, but I can't wrap my head around it.

Here's the current calculation:

.my-class {
    --columns: 3;
    --gap: 16px;

    width: calc((1 / var(--columns) * 100%) - ((1 - 1 / var(--columns)) * var(--gap)));
}

Below is an example demonstrating how this works within a fixed-width container (768px wide).

.toCalc {
  --cols: 3;
  --gap: 16px;
  
  width: calc((1 / var(--cols) * 100%) - ((1 - 1 / var(--cols)) * var(--gap)));
  
  background: blue;
  height: 150px;
}

.container {
  width: 768px;
  height: 300px;
  background: grey;
  display: flex;
  gap: 16px;
}
<div class="container">
  <div class="toCalc">
    This is content
  </div>
  <div class="toCalc">
    This is content
  </div>
  <div class="toCalc">
    This is content
  </div>
</div>

Trying to convert this to SCSS has proven challenging:

@function calcWidth($cols, $gap) {
  @debug "1/cols: #{1/$cols}";
  @debug "(1/cols) * 100%: #{(1/$cols) * 100%}";
  @debug "1 - (1/cols): #{1 - (1/$cols)}";
  @debug "(1 - (1/cols)) * gap: #{(1 - (1/$cols)) * $gap}";

  $result = ((1/$cols) * 100%) - ((1 - (1/$cols)) * $gap);

  @debug "full result: #{$result}";

  @return $result;
}

...

.my-class {
  // Converted css properties (--var) to SCSS variables ($var)
  $cols: 3;
  $gap: 16px;

  width: calcWidth($cols, $gap);
}

When using cols = 3 and gap = 16px, the debug messages show:

DEBUG: 1/cols: 0.33333
DEBUG: (1/cols) * 100%: 33.33333%
DEBUG: 1 - (1/cols): 0.66667
DEBUG: (1 - (1/cols)) * gap: 10.66667px
DEBUG: full result: 22.66667px // <------------ This is not the same as we see?!

The debug messages seem technically correct, so why does the code give us a width value of 245.33px instead?


Update I realized I left out the % from the function calculation initially.

However, upon adding it back in, SASS throws an error about incompatible units:

SassError: Incompatible units: 'px' and '%'.

Answer №1

Thanks goes out to both @clod9353 and a fresh pair of eyes in the morning. I discovered that breaking the original calculation into smaller pieces and wrapping it within calc() made all the difference!

I spent quite some time adjusting the width of my elements to match specific calculations and adding the % symbol really helped clarify things for me.

Fortunately, my container has a fixed width which makes it easier to visualize and work with concrete numbers.

Here's the Breakdown:

The original formula:

1 / var(--cols) * 100%) - ((1 - 1 / var(--cols)) * var(--gap))

Let's say we're working with 3 columns and a gap of 16px for this example.

First part:

1 / 3 * 100% equals 33.333...%

This means each column will be one-third of the width since it's now represented as a percentage.

Second part:

(1 - 1 / 3) * 16px

This portion creates a 16px gap between columns by applying it to only 2 out of the 3 columns.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The legend in the fieldset is not displaying correctly due to overflow issues

Within my fieldset, there is a legend structured as shown below: <fieldset class="fieldsetStyle"> <legend class="fieldsetLegendStyle"> <div> <h:outputText value="#{msgs.LABEL_AJOUTER_U ...

Enhancing the Appearance of MUI Date Calendar

I'm in the process of creating a calendar similar to mui's <DateCalendar />, and I want to customize the header from 'S M T W T F S' to 'Sun Mon...' as well as adjust the position of the arrows. Before: https://i.sstat ...

The background image in the anchor tag is not visible

Here is the code snippet in question: <div id="button-wrapper"> <a id="matematica"></a><br> <a id="romana">s</a><br> <a id="informatica">s</a><br> </div> This is the CSS applie ...

Take the information entered in an HTML form, add it to a JSON object, and save it in a MYSQL

I'm currently working on extracting data from a user registration form in HTML, converting it to JSON format, and then storing it in MySQL. Your assistance with this process would be greatly appreciated. HTML <form id="myForm" action="userInf ...

How can I create a detailed highchart map of Korea that accurately includes Dokdo in its design?

I am currently working on a project to create a comprehensive map of Korea using highchart. One major challenge I have encountered is the absence of Dokdo on the standard map of Korea provided by highchart. Is there a way for me to develop a map that inc ...

I possess a pair of UI tabs. Whenever a button located outside the tab is clicked, I am required to activate a distinct tab

As a beginner in Javascript, I recently encountered an issue with a UI tab element that contains two tabs. My goal is to create a button that, when clicked, will scroll up and activate the second tab. <style> .tab-container { overflow-x: ...

Eliminating Unnecessary Stylesheets in Vite and Vue Website

When working on the Vite-Vue application, I noticed that the styles I implemented for both index.html and Vue components/views are showing up as crossed out in the browser. Additionally, many of the styles I added to the components/views are also being cro ...

How can I access the value of a textbox within a dynamically generated div?

In my project, I am dynamically creating a div with HTML elements and now I need to retrieve the value from a textbox. Below is the structure of the dynamic content that I have created: <div id="TextBoxContainer"> <div id="newtextbox1"> // t ...

Retrieve the div element using the jQuery selector for both the id and class

This is the structure I have set up: <div id="list_articles"> <div id="article"> <label>Select:</label><input type="checkbox" class="checked_art" id="1001" /> <div id="hide" style="display:none;" class="1001"> ...

Ways to troubleshoot Contact Form not progressing to the following validation step

The validation for the first two inputs, title and name, is functioning correctly. However, there is an issue with the page refreshing every time validation occurs. After validating the name field, the email field, as well as other fields such as dropbox, ...

Is it feasible to customize the css3 resize feature?

I'm curious - is there a way to customize the CSS3 resize property? div { resize: both; overflow: auto; } Basically, I am looking for a horizontal resize with a vertical bar instead of the default handle. Take a look at the images for reference. ...

Is there a way to automatically refresh the page and empty the input fields after clicking the submit button on the contact form?

My knowledge of PHP and js is limited, so I may require additional guidance in incorporating those codes. Lately, I've been developing a contact form and making good progress. However, I'm struggling with figuring out how to refresh the page or ...

Combining multiple .php files in a single div

Hey there! I have a piece of code that allows me to load a PHP file into a div. It's currently functional, but I'm facing a challenge where I need to load the next file into the same div. <script type="text/javascript"> $(function() { ...

Issue with sending an ajax post request using Jquery

The jquery ajax request below is not working as expected: $(document).ready(function(){ var friendrequest = $(".friendrequest").val(); $(".afriendreq").click(function(){ $(".afriendreq").hide(); ...

What is the difference between class at DOM and className at component?

When passing the className props to the child component, sometimes the className for the active link is not correctly reflected in the DOM element during production: The child component (Link) receives the className prop for the active link from the paren ...

Shifting text higher to the <h1> tag using CSS

I'm currently attempting to move the paragraph header closer to my h1 title. I'm struggling with incorporating the position function and have tried using padding without success. On the image, I am aiming to position the text "Where every connec ...

What steps can be taken to properly display dateTime values in a data table when working with JavaScript (VueJS) and PHP (Laravel)?

I am facing an issue where I am unable to save user inputted date-time values from a modal into a data table. Despite receiving a success message, the dateTime values are not being added to the table. My payload only displays the state and approval fields ...

The CSS variables set within the :root section of styles.scss are not recognized as valid

Trying to implement global colors using CSS variables in my Angular 11 app. The styles.scss file contains: :root{ --primary : #0b68e8; --secondary:#ABCFFF; } .test-class{ background: var(--primary); } However, when applying this class in one ...

Discovering the values within a separate JSON object

I have a collection of json objects that include information about different languages and user details. Languages User Details The user details contain a field for languages, which can have multiple values. Below is a sample json: $scope.languages = ...

The Bootstrap menu is having trouble collapsing properly

We're currently in the process of constructing a website using bootstrap, but we've encountered an issue with the menu bar. Upon visiting , you'll notice that the top menu functions properly and collapses perfectly when viewed on mobile dev ...