伪类选择器使用
:first-child 选择某个元素的第一个子元素(IE6不支持)
:last-child 选择某个元素的最后一个子元素
:first-of-type [CSS3]选择一个上级元素下的第一个同类子元素
:last-of-type [CSS3]选择一个上级元素的最后一个同类子元素
:only-child [CSS3]选择的元素是它的父元素的唯一一个了元素(IE6-8不支持)
:only-of-type [CSS3]选择一个元素是它的上级元素的唯一一个相同类型的子元素(IE6-8不支持)
:nth-child() [CSS3]选择某个元素的一个或多个特定的子元素(IE6-8不支持)
:nth-last-child() [CSS3]选择某个元素的一个或多个特定的子元素,从这个元素的最后一个子元素开始算(IE6-8不支持)
:nth-of-type() [CSS3]选择指定的元素(IE6-8不支持)
:nth-last-of-type() [CSS3]选择指定的元素,从元素的最后一个开始计算(IE6-8不支持)
nth-child伪类选择器运用
odd 和 even 是可用于匹配下标是奇数或偶数的子元素的关键词(第一个子元素的下标是 1)
<template>
<view class="container">
<view class="cont_one">
<view v-for="(item,index) in 10" :key="index">{{index}}</view>
</view>
<view class="cont_two">
<view v-for="(item,index) in 10" :key="index">{{index}}</view>
</view>
<view class="cont_three">
<view v-for="(item,index) in 10" :key="index">{{index}}</view>
</view>
<view class="cont_four">
<view v-for="(item,index) in 10" :key="index">{{index}}</view>
</view>
</view>
</template>
<script>
</script>
<style>
.container>view{
display: flex;
align-items: center;
margin:20rpx;
}
.container>view>view{
padding:5rpx 10rpx;
margin-right:10rpx;
border:1rpx solid #000000;
border-radius: 15rpx;
font-size: 28rpx;
}
/* 奇数 */
.cont_one>view:nth-child(odd){
/* 等价于 nth-child(2n+1) */
background-color: red;
}
/* 偶数 */
.cont_two>view:nth-child(even){
/* 等价于 nth-child(2n)*/
background-color: red;
}
/* 前两个 */
.cont_three>view:nth-child(-n+2){
background-color: red;
}
/* 除前一个,因为下标从1开始 */
.cont_four>view:nth-child(n+2){
background-color: red;
}
</style>
结果
伪元素:before和:after使用
在这里插入代码片
<template>
<view class="container">
<!-- 点击才做操作 -->
<view class="cont_one">active伪元素</view>
<!-- 插入元素在后面 -->
<view class="cont_two">after伪元素默认用法</view>
<!-- 插入元素在后面 -->
<view class="cont_three">after伪元素定位用法</view>
<!-- 插入元素在前面 -->
<view class="cont_four">before伪元素默认用法</view>
<!-- 插入元素在前面 -->
<view class="cont_five">before伪元素定位用法</view>
</view>
</template>
<script>
</script>
<style>
.container{
margin:20rpx;
}
.cont_one,.cont_two,.cont_three,.cont_four,.cont_five{
width:500rpx;
height: 60rpx;
display: flex;
margin-top:20rpx;
align-items: center;
justify-content: center;
font-size: 28rpx;
border-radius: 10rpx;
border: 1rpx solid #000000;
}
/* 点击时显示红色背景,松开时红色背景消失 */
.cont_one:active{
background-color: red;
}
/* 插入元素在后面 */
.cont_two:after{
content: '默认使用';
color: red;
}
/* 插入元素在后面 */
.cont_three:after{
content: '定位使用';
position: relative;
left:20rpx;
top:20rpx;
color: red;
}
/* 插入元素在前面 */
.cont_four:before{
content: '默认使用';
color: red;
}
/* 插入元素在前面 */
.cont_five:before{
content: '定位使用';
position: relative;
right:20rpx;
top:20rpx;
color: red;
}
</style>
结果如下