一、calc()函数介绍
calc() 函数用于动态计算长度值
- 需要注意的是,运算符前后都需要保留一个空格,例如:width: calc(100% - 10px);
- 任何长度值都可以使用calc()函数进行计算;
- calc()函数支持 “+”, “-”, “*”, “/” 运算;
- calc()函数使用标准的数学运算优先级规则;
通常用于 保持全屏
,如下代码所示;
<style>
* {
margin: 0;
padding: 0;
}
header, footer {
width: 100%;
height: 50px;
line-height: 50px;
text-align: center;
background-color: rgb(23, 124, 192);
color: #fff;
}
section {
width: 100%;
height: calc(100vh - 100px);
text-align: center;
background-color: rgb(22, 136, 121);
color: #fff;
}
</style>
<header>头部标题</header>
<section>中间区域</section>
<footer>底部内容</footer>
二、calc()函数与val()联合使用
clac()函数可以通过val()接收style中传递的参数名为
--xx
的变量,常用于动画特效。
<style>
* {
margin: 0;
padding: 0;
}
.container {
width: 100vw;
height: 100vh;
display: flex;
background: #111;
}
.container .box {
margin: 5px;
width: calc(10px * var(--m));
height: calc(10px * var(--m));
background: rgba(0, 255, 0, 0.25);
}
</style>
<div class="container">
<div class="box" style="--m:1"></div>
<div class="box" style="--m:2"></div>
<div class="box" style="--m:3"></div>
<div class="box" style="--m:4"></div>
<div class="box" style="--m:5"></div>
<div class="box" style="--m:6"></div>
<div class="box" style="--m:7"></div>
<div class="box" style="--m:8"></div>
<div class="box" style="--m:9"></div>
<div class="box" style="--m:10"></div>
</div>