在HTML页面的DIV布局中,如果我们把DIV的宽度当做一个计算公式,让浏览器去自动去计算它们的值是不是很有意思呢?那么今天就说一下,CSS中的一个关于计算的函数 calc()
calc() 函数介绍
calc():英文单词calculate(计算)的缩写,是 css3 新增加的一个功能。它可以动态的设置元素样式中border、margin、pading以及 width 等属性的值。
calc() 函数定义
1、calc() 函数可以计算任何长度的值
2、calc() 函数支持 "+", "-", "*", "/" 运算;
3、calc() 函数使用标准的数学运算优先级规则;
4、特别要注意的是,运算符前后都需要一个空格。
5、现代浏览器都支持 calc() 函数
calc() 函数的语法
calc(expression)
expression:一个数学表达式,会返回表达式所计算出的值
示例:
width: calc(100% - 10px);
calc() 函数用法示例
示例1:
<html>
<head>
    <meta charset="utf-8">
    <title>博客标题</title>
    <style>
        .div{
            width: 100px;
            height: 100px;
            position: relative;
            background-color: bisque;
        }
        .div2{
            width: 20px;
            height: 20px;
            background-color: blueviolet;
            position: absolute;
            /*计算结果:60px*/
            top: calc(100% - 40px) ;
            /*计算结果:50px*/
            left: calc(100% - 50px) ;
        }
    </style>
</head>
<body>
    <div class="div">
        <div class="div2"></div>
    </div>
</body>
</html>
运行结果如下图:

CSS代码解释:
top: calc(100% - 40px) ; left: calc(100% - 50px) ;
相当于
top: 60px; left: 50px;
示例2:
<html>
<head>
    <meta charset="utf-8">
    <title>博客标题</title>
    <style>
        .div{
            width: 200px;
            height: 100px;
            position: relative;
            background-color: bisque;
        }
        .div2{
           width:50px;
           height: 100px;
           background-color: aqua;
           display: inline-block;
        }
        .div3{
           width: calc(100% - 60px);
           height: 100px;
           background-color: brown;
           display: inline-block;
           float: right;
        }
    </style>
</head>
<body>
    <div class="div">
        <div class="div2"></div>
        <div class="div3"></div>
    </div>
</body>
</html>
运行结果如下图:

css代码解释:
width: calc(100% - 60px);
相当于
width: 140px;

