我们想要实现页面自适应布局时,通常因为margin的存在,而比较麻烦;有时候想要实现宽度自适应的输入框时,也因为padding或margin的存在,而相当繁琐,同时由于浏览器兼容性而导致最终效果不一致。css3新添加属性box-sizing,在一定程度上解决了上面的问题,而在今天的文章中我们来通过css3新增加的另外一个属性calc()来实现适应布局。
calc()是css3新添加属性,它可以让你使用一个算术表达式来表达长度值,这意味着可以用它来定义div的宽度,并设置margin、padding、border等。
calc()的运算规则
实例1:定位在页面上的块元素,含有外边距
.banner {
}
实例2:自动调整大小的表单,又适应容器
input {
}
#formbox {
}
<form>
</form>
浏览器兼容性
This is why you see examples like this:
width: calc(100%/3 - 2*1em - 2*1px);
That’s actually the minimum number of characters you need to write that particular expression, so far as I can tell. Given the grammar requirements, you could legitimately rewrite that example like so:
width: calc(100% / 3 - 2 * 1em - 2 * 1px);
…but not like so:
width: calc(100%/3-2*1em-2*1px);