calc() 和 :nth-child()

202 阅读1分钟

calc()函数:动态计算长度(CSS3新增函数)

l1:已知元素宽高,令其居中
.parent{
    width:500px;
    height:500px;
    position:relative;
    background-color:blue;
}
.child{
    width:200px;
    height:200px;
    position:absolute;
    background-color:yellow;
    top:calc(50% - 100px);
    left:calc(50% -100px); // 此处100px为child宽度的一半
}
<div class="parent">
    <div class="child"></div>
</div>

ATTENTION:

1、运算符表达式中有“+”,“-”运算符的,前后必须要有空格。例如:width: calc(100% - 10px);

2、任何长度值都可以使用calc()函数进行计算;

3、calc()函数支持 “+”, “-”, “*”, “/” 运算;

3、calc()函数使用标准的数学运算优先级规则;

:nth-child(an+b):匹配符合表达式的元素

用法:

  • 0n+3 或简单的 3 匹配第三个元素。
  • 1n+0 或简单的 n 匹配每个元素。(兼容性提醒:在 Android 浏览器 4.3 以下的版本 n 和 1n 的匹配方式不一致。1n 和 1n+0 是一致的,可根据喜好任选其一来使用。)
  • 2n+0 或简单的 2n 匹配位置为 2、4、6、8...的元素(n=0 时,2n+0=0,第 0 个元素不存在,因为是从 1 开始排序)。你可以使用关键字 even 来替换此表达式。
  • 2n+1 匹配位置为 1、3、5、7...的元素。你可以使用关键字 odd 来替换此表达式。
  • 3n+4 匹配位置为 4、7、10、13...的元素。
l2div:nth-child(2n+1) // 寻找第1,3,5...div元素集合
div:nth-child(odd) // 同上
div:nth-child(2n) // 寻找第2,4,6...div元素集合
div:nth-child(even)
div:nth-child(1) // 寻找的第一个div