1. Understand the css calc() function
The CSS calc() function is a function used to calculate the value of a CSS property. It can use mathematical expressions in CSS property values to achieve the effect of dynamically calculating property values. The calc() function can use the four basic mathematical operators of addition, subtraction, multiplication and division to calculate attribute values, and can also use parentheses to change the priority.
2. Notes on using calc()
serial number | Notice | Remark |
1 | There needs to be a space before and after the operator | Example:width: calc(100% - 10px) ; |
2 | Any length value can be calculated using the calc() function | |
3 | The calc() function supports "+", "-", "*", "/" operations; | |
4 | The calc() function uses standard mathematical operation precedence rules; |
3. DEMO
3.1. Calculate width
div {
width: calc(100% - 20px);
}
In this style rule, the width of the div element is the width of the entire parent container minus 20px. When the browser window changes size, the width of the div element is automatically recalculated to fit the new window size.
3.2. The calc() function also supports calculation of multiple values.
div {
padding: calc(10px + 2%) calc(20px - 5%);
}
In this style rule, the top and bottom padding of the div element is 10px plus 2% of the width of the parent container, and the left and right padding is 20px minus 5% of the width of the parent container.
3.3. Method of binding styles
3.4. Nested use
width: calc((50% + 100px) * 20px);
3.5. Use calc for inline styles of mini programs
<view :style="'height: calc(100vh - 168rpx);'" >
3.6. Use of multiple units
<view :style="'height: calc(100vh - 168rpx - 30px);'">
4. Compatibility
5. Related content
serial number | Attributes | describe | demo |
1 | calc() | Calculate CSS property values | width: calc(100% - 50px); |
2 | min() | Returns the minimum value in a set of values | width: min(50%, 400px); |
3 | max() | Returns the maximum value in a set of values | height: max(200px, 50vh); |
4 | clamp() | Implement adaptive responsive design for values within a certain range | font-size: clamp(16px, 2.5vw, 24px); |
6. Welcome exchanges and corrections
7. Reference links
Modern CSS Solution: CSS Mathematical Functions - Zhihu
CSS calc() function | Newbie tutorial
Use of css3 height calculation function cal_css function calc()_weixin_39968852's blog-CSDN blog