需求
需求1
写了一个如下的伪元素,但是在页面上却没有显示
&::before{
content: 111;
position: absolute;
right: 0;
top:0;
width: 36px;
height: 36px;
}
原因
- 伪元素必须存在content属性;
- content属性属性值为字符串!
number类型不显示
;
- content属性属性值为字符串!
实现
&::before{
content: '111';
position: absolute;
right: 0;
top:0;
width: 36px;
height: 36px;
}
需求2:
想要在input输入框的前面加一个icon,就是用了伪元素选择器,但是发现不起作用;
原因
单标签不能使用伪元素选择器!!!
实现
在input外面包一个盒子再使用伪元素定位上去!
知识点
伪元素的content属性值
既然上述需求遇到了content属性值问题,我们来具体看下伪元素的content属性到底可以接收什么样的值吧
[1]字符串
-
伪元素的content属性值可以是字符串;
-
常用来将
单位
等作为伪元素跟随在数值后面,这样无需添加dom元素;-
&::before{ content: '元'; position: absolute; right: 0; top:0; width: 36px; height: 36px; }
-
[2]url
伪元素的属性值可以是一个url方法,插入url图片;
-
&::before{ content:url('../../../static/images/douyin2.png'); position: absolute; width: 36px; height: 36px; right: 0; top:0; }
-
缺点:通过伪元素引入的图片
无法设置图片的大小
,只能使用默认图片; -
若是想通过伪元素设置图片,可以通过背景图来设置;
-
&::before{ content:''; position: absolute; background: url('../../../static/images/douyin2.png'); width: 36px; height: 36px; background-size: cover; right: 0; top:0; }
-
通过background-size来控制图片大小;
-
[3]attr
伪元素content属性值可以是attr方法,引入标签的属性值;
-
一般用于动态设置伪元素的属性值!
-
<li class="item" :class="classObj[item.mediaType]" slot="reference" data-content='1'>
-
&::before{ position: absolute; content:attr(data-content); right: 0; top:0; }
-
注意点:
-
css的attr属性虽说是可以动态设置css变量,但是必须
结合伪元素的content属性使用
,否则获取不到! -
&::before{ position: absolute; content:'111'; color:attr(data-content); right: 0; top:0; }
- 颜色没有变为红色,通过控制台发现获取失败!
-