掌握好这几个css属性,少写100行js代码

时间:2022-07-22
本文章向大家介绍掌握好这几个css属性,少写100行js代码,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.calc函数

calc可动态设置某个元素的长度。

html{
    font-size:calc(100vw / 8)
}
.main{
    width:100%;
    height:calc(100vh - 200px)
}

比如上述代码,把main元素的高度就设置为当前窗口的高度减去200px,字体大小也可用于此函数实现自适应字体;这个函数可用于所有css长度的属性

2.attr函数

这个函数用于获取元素的属性的值,我常用于在before等伪类样式中。

ul li::before {
 position: absolute;
 color: #fff;
 left: calc(100% - 50px);
 font-size: 12px;
 content: attr(data-tip);
 line-height: 40px;
 transform: scale(0);
 transition: all 0.8s;
}

html

 <li data-tip="about"><a href="">关于我们</a></li>
 <li data-tip="center"><a href="">项目中心</a></li>
 <li data-tip="media"><a href="">媒体报道</a></li>

attr就获取li元素中data-tip属性,然后加入到before中,注意不是所有的属性都可以用attr获取。

3.nth-child()

这个属性大家应该用的还是比较多,可用于选择特定的元素。

ul li:nth-child(odd){background-color:green;}/*设置单行样式*/

ul li:nth-child(even){background-color:gray}/*设置双行样式*/

ul li:nth-child(3n){background-color:green;}/* 3,6,9,12... */

ul li:nth-child(4){background-color:green;}/*单独设置第四个li*/

ul li:nth-child(3n+2){background-color:green;}/*匹配2,5,8,11...*/

ul li:nth-child(n+6){background-color:green;}/*从第六个li开始匹配*/

ul li:nth-child(-n+6){background-color:green;}/*匹配1-6的元素*/

ul li:nth-child(n+3):nth-child(-n+5){background-color:green;}/*匹配3-5的元素*/

ul li:nth-child(3n-1){background-color:green;}/*匹配(3-1),(6-1),(9-1)....*/

4.invalid和vaild

这两个css属性主要配合文本框的pattern的属性使用,验证成功时加载vaild样式,失败加载invaild样式

html

<input type="text" placeholder="请输入你的手机" pattern="^1[3456789]d{9}$" required>

css

input:invalid{background:Red}
input:valid{background:green}

5.filter: grayscale

这个属性主要是修改元素的黑白度,比如某人去世,让界面变灰,就可以使用此属性

html{filter:grayscale(100%);}

这样就可以使得页面变成灰色,适用于悼念某人的情况下。

6.linear-gradient

此属性配合background使用,实现渐变的背景

div{background-image:linear-gradient(to right, red , yellow); }

上述代码设置div从左侧到右侧,从红色到黄色的渐变。