Using a percentage value in a CSS calculation

When using a percentage value in css calc, how does calc determine whether it is referencing the width or height?

.container {
    width: calc(100% - 2vw); // Is 100% referring to width or height here?
}

It is assumed that it refers to either width or height depending on the property being accessed, such as width in this case. However, what if you want to perform calculations based on a different property? For example, setting the width based on a calculation involving the height? Like setting the container width to be 1.5 times the height?

Answer №1

As stated in the specification

The calc() function calculates the expression with all components computed.

It's important to note that percentages are not resolved at computed-value time, therefore they are not resolved in calc() expressions. For example, calc(100% - 100% + 1em) resolves to calc(1em + 0%), not simply 1em. Special rules for computing percentages in a value apply when a calc() expression contains percentages.

When using percentages inside calc(), they behave as if you aren't using calc() at all. So, width:100% is the same as width:calc(100%) which is also equivalent to calc(50% + 50%). When adding another unit like width:calc(100% - 2em), it calculates as width:100% and then subtracts 2em from it.

In essence, calc() is helpful when combining percentage and non-percentage values to achieve precise results, such as removing 10px from 50% of the total width with width:calc(50% - 10px).


What if you need to perform calculations based on a different property? Like setting the width based on a calculation involving height?

This cannot be done with calc(). CSS does not allow for such operations. One could explore using JavaScript, implementing hacks to maintain ratios between width and height, or utilizing CSS variables to assign the same value to multiple properties.


Check out this related question where the misuse of calc() combined with CSS variable is discussed: Calc() outputting unexpected value

Answer №2

Addressing the second aspect of the query:

As an example, adjusting the width based on a specific calculation of height? Perhaps setting the container width to be 1.5 times the height?

This can be accomplished using the aspect-ratio property:

.container {
  text-align: center;
  height: 200px;
  /* defining width / height ratio */
  aspect-ratio: 1 / 1.5;
  background: lightgray;
}
<div class="container">
  some content
</div>

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

Tips for positioning "THANK YOU" in the center

and this is a snippet of my coding <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class=" ...

What can I do to prevent my CTA image with a width of 100% from distorting when I change the height?

Creating a website and in need of a CTA image? Utilizing Bootstrap 4 along with custom CSS to tweak the appearance, I've set it to occupy the entire width of the screen using width: 100%;. As the screen size changes, the image remains responsive, adju ...

Retrieve the CSS class definition using the console in the Chrome Developer Tools

Is there a way to automatedly extract CSS class definitions from Chrome Developer Tools? I want to retrieve the styles defined in a specific class name, similar to how it is displayed in the Styles tab on the right-hand side. I know about the getComputedS ...

Positioning a text field and a button adjacent to each other within the same row

My challenge is to consistently position a textfield and a button side by side. The requirement is for the button to always be on the right side of the screen, while the textfield should take up the remaining width on the left side. I initially tried setti ...

Tips for creating CSS from the Google Chrome inspector for future use

Hey there, I spent the evening debugging my JSF page and noticed some changes in appearance when checking/unchecking options in Google Chrome Inspector. I want to create a new CSS file based on these checked options and save it for use in my web applicat ...

Underline Rows in CSS

When designing my website, I decided to organize the content into rows using CSS instead of tables. To create a line separating each row, I used height:px; for each row manually. However, this method resulted in the line jumping around inconsistently acr ...

Updating the functionality of one-page scrolling - changing to overlap instead of sliding upwards

Hello, I am currently utilizing a JavaScript library to create a website with full page scrolling. If you want to know about the library, check out this link: For those interested, here is an example of my work on jsfiddle: http://jsfiddle.net/aLjLjxux/ ...

Text misalignment in div elements across various browsers

Having an issue with the alignment of text in different browsers. I'm attempting to make the comments line and the "like" heart line line up properly, similar to the layout in the lower right corner shown in this image taken from Firefox: However, wh ...

What is the best way to customize a div depending on the validation status of all reactive form fields within it?

I am facing a challenge with a rather complex form that contains multiple fields. Some of these fields are used to create logical blocks, and I would like to emphasize the surrounding div if any of these included fields are invalid. Can you suggest the bes ...

Creating a Dynamic Login Panel Using HTML, CSS, and Jquery

Designing a dynamic sliding login panel utilizing Html, CSS, and jquery alongside various plugins. Check it out here: http://24.125.42.135/ When activated, the bar smoothly pushes down the content (click on the login option at the top right corner). This ...

What steps do I need to follow to create a unique angular component that allows for customizable width using CSS styles?

The instructions on this website suggest that the width of the side-nav can be changed using CSS like so: md-sidenav { width: 200px; } This leads me to wonder, can I apply standard CSS properties such as width, position, etc... to custom components wi ...

Setting a background image at 50% opacity on a container-fluid: What you need to know

Just to clarify, I'm not looking for someone to solve this problem for me. I've been trying to figure it out on my own but haven't had any luck. I've searched for similar solutions online, but none of them have worked for what I need sp ...

The concept of Nested DIVs and their impact on Element Height

Trying to divide this page into blocks with checkbox options in a 4x3 layout. The issue is that setting the "columns" to 100% height makes it 100% of the parent's parent, not the parent div. Any suggestions? <div id="left" style="width:50%;height: ...

Astro Project experiencing issues with loading SRC folder and style tags

After setting up a brand new astro repository with the following commands: npm create astro@latest npm run dev I encountered an issue where the default project template failed to display correctly on my computer. Here is how the page appeared: https://i. ...

A <mat-card> does not have a raised appearance because it lacks a border

Looking for help with my HTML code. Here's the setup: <mat-card> <mat-card-content> <code>{{file}}</code> </mat-card-content> </mat-card> But when the mat-card element is rendered, it's not ra ...

What is the process for updating the CSS style of every other piece of data (such as an image) retrieved

Is it possible to utilize PHP code when retrieving data from a MySQL database in order to have every other record display with unique CSS formatting? For instance, I am incorporating images similar to this in my comment system: http://prntscr.com/3hpiep ...

How can I customize the appearance of the file input button in Angular Material?

Despite browsing numerous similar questions, I have yet to find a solution to my issue. My setup includes Angular 11, Angular Material 8, and a file input structured like this: <div class="form-group"> <input #myInput type="fil ...

Avoiding the issue of table row height glitch when adding to the DOM

I have a table that I load first, and then I dynamically append tags asynchronously. However, when the tags are appended, the height of the table row seems to shift up. How can I prevent this from happening? https://i.sstatic.net/Dx3G4.gif I've atte ...

How do I make the dropdown menu in a navbar stretch horizontally to cover the entire width of the page container?

When I hover over an item in the navbar, a horizontal dropdown menu currently opens as shown below (note the width of the dropdown menu): https://i.sstatic.net/824OVkWT.png What am I aiming for? I want to expand the horizontal dropdown menu like in the i ...

When using an iPhone 6+ in landscape mode with tabs open on Mobile Safari running iOS 8, the Bootstrap navbar-fixed-top may experience difficulty in

Encountered an issue with Bootstraps navbar-fixed-top on iPhone 6+ in landscape mode on iOS 8 when multiple tabs are open. To replicate the bug: 1) Visit http://getbootstrap.com/examples/navbar-fixed-top/ on iPhone 6+ in landscape mode with another tab ...