How to use calc in css3?

In CSS, the calc() function is used to perform mathematical calculations to dynamically calculate values ​​in CSS properties. This function is usually used to define the width, height, margin, padding and other properties of the element so that the final result can be calculated based on the values ​​of other properties.

The syntax of the calc() function is as follows:

property: calc(expression);

Where property is the name of the CSS property and expression is the mathematical expression to be evaluated. This expression can include basic mathematical operations such as addition, subtraction, multiplication, and division, as well as percentages and other units.

Here are some examples showing common uses of the calc() function:

Calculate width or height:

width: calc(100% - 20px);
height: calc(50vh - 30px);
// vh相对于浏览器窗口,%相对于父元素大小

Calculate margins or padding:

margin: calc(10px + 5%);
padding: calc(2em - 10px);

Combine multiple attribute values:

font-size: calc(16px + 2vmin - 5%);

Using calc() in animations:

transition: width 0.5s ease-in-out, height 0.5s ease-in-out, opacity 0.3s linear;

Note that whitespace in calc() is significant, and mathematical operators must be surrounded by whitespace. Additionally, supported units and mathematical operators depend on browser support, but common units (such as pixels, percentages, ems, rem, etc.) as well as addition, subtraction, multiplication, and division are generally supported.

In short, the calc() function is a very useful tool in CSS that can help you implement dynamic calculations and responsive design in style sheets.

Guess you like

Origin blog.csdn.net/weixin_43160662/article/details/132843183