::before和::after伪元素的常见用法

装载于:详细用法请参考原文

一、介绍

  1. css3为了区分伪类和伪元素,伪元素采用双冒号写法。
  • 常见伪类——:hover,:link,:active,:target,:not(),:focus。
  • 常见伪元素——::first-letter,::first-line,::before,::after,::selection。
  1. ::before和::after下特有的content,用于在css渲染中向元素逻辑上的头部或尾部添加内容。

  2. 这些添加不会出现在DOM中,不会改变文档内容,不可复制,仅仅是在css渲染层加入。

  3. 所以不要用:before或:after展示有实际意义的内容,尽量使用它们显示修饰性内容,例如图标。

二、content属性
::before和::after必须配合content属性来使用,content用来定义插入的内容,content必须有值,至少是空。默认情况下,伪类元素的display是默认值inline,可以通过设置display:block来改变其显示。

content可取以下值。
1、string
使用引号包一段字符串,将会向元素内容中添加字符串。如:a:after{content:""}

<!DOCTYPE html>
<meta charset="utf-8" />
<style type="text/css">
p::before{
    content: "《";
    color: blue;
}
p::after{
    content: "》";
    color: blue;
}
</style>
<p>平凡的世界</p>

效果:《平凡的世界》

2、attr()
通过attr()调用当前元素的属性,比如将图片alt提示文字或者链接的href地址显示出来。

<style type="text/css">
a::after{
    content: "(" attr(href) ")";
}
</style>
<a href="http://www.cnblogs.com/starof">starof</a>

效果:http://www.cnblogs.com/starof

3、url()/uri()
用于引用媒体文件。

举例:“百度”前面给出一张图片,后面给出href属性。

<style>
a::before{
    content: url("https://www.baidu.com/img/baidu_jgylogo3.gif");
}
a::after{
    content:"("attr(href)")";
}
a{
    text-decoration: none;
}
</style>
---------------------------
<body>
<a href="http://www.baidu.com">百度</a>
</body>

效果:
在这里插入图片描述
4.做出图形效果(常用)
举例:一个六角星

<style>
#star-six {
  width: 0;
  height: 0;
  border-left: 50px solid transparent;
  border-right: 50px solid transparent;
  border-bottom: 100px solid red;
  position: relative;
}
#star-six::after {
  width: 0;
  height: 0;
  border-left: 50px solid transparent;
  border-right: 50px solid transparent;
  border-top: 100px solid red;
  position: absolute;
  content: "";
  top: 30px;
  left: -50px;
}
</style>
<body>
<div id="star-six"></div>
</body>

实现原理:
#star-six的div是一个正三角行,#star-six::after是一个倒三角形,通过绝对定位,调整其位置即可实现六角星的效果。
举例:" + “和” - "

button.accordion:after {
				content: '\002B';
				color: #777;
				font-weight: bold;
				float: right;
				margin-left: 5px;
			}

button.accordion.active:after {
			content: "\2212";
		}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值