定义:
calc() 函数用于动态计算长度值。
用法 :
特别注意:
- 运算符前后都需要保留一个1
空格
,例如:width: calc(100% - 10px); - 任何长度值都可以使用calc()函数进行计算;
- calc()函数支持 “+”, “-”, “*”, “/” 运算;
- calc()函数使用标准的数学运算优先级规则;
实例:
如计算元素的宽高
.parent{
height: 300px;
width: 100%;
position: relative;
background-color: #ccc;
}
/*通过设置calc属性控制元素的宽高*/
.children {
height: calc(100% - 50px);
width: calc(50% - 100px);
border: 1px solid red;
}
<body>
<div class="parent">
<div class="children"></div>
</div>
</body>
效果展示:
children元素的宽高可以由calc属性的值进行控制
处理布局中的定位:
.parent{
height: 300px;
width: 100%;
position: relative;
background-color: #ccc;
}
.children {
width: 50px;
height: 50px;
top: calc(50% - 25px);
left: calc(50% - 25px);
position: absolute;
border: 1px solid red;
}
效果展示:
children元素定位的位置页可以由calc的值进行控制,children元素水平垂直居中