CSS常用伪元素使用详解

首先伪类是用单冒号表示:如:link, :visited, :hover, :active, :focus, :first-child, :last-child, :nth-child, :nth-last-child, :not()

然后伪元素用双冒号表示:如::first-letter, ::first-line, ::before, ::after

1.::first-letter

选中元素的首字符,为其设置样式

<!DOCTYPE html>
<html>
<head>
<style>
p:first-letter
{
font-size:200%;
color:#8A2BE2;
}
</style>
</head>
<body>

<h1>Welcome to My Homepage</h1>
<p>My name is Donald.</p>
<p>I live in Duckburg.</p>
<p>My best friend is Mickey.</p>

</body>
</html>

2. ::first-line

选中元素的地一行

<!DOCTYPE html>
<html>
<head>
<style>
p:first-line
{
background-color:yellow;
}
</style>
</head>

<body>
<h1>WWF's Mission Statement</h1>
<p>To stop the degradation of the planet's natural environment and to build a future in which humans live in harmony with nature, by; conserving the world's biological diversity, ensuring that the use of renewable natural resources is sustainable, and promoting the reduction of pollution and wasteful consumption.</p>
</body>
</html>

3.::before和::after

::before和::after可在元素前后添加内容,使用十分灵活,没有做不到,只有想不到!!

需要注意的是: 1.::before和::after添加的内容都是放在该元素的子元素的最前面或者最后面的!

                           2.::before和::after下特有的content不会改变文档内容,仅作为一种渲染使用!

下面介绍::before和::after的三种用法

1)在元素的前面或者后面添加一些字符内容

<!DOCTYPE html>
<html>
<head>
<style>
p:before
{
content:"台词:";
}
</style>
</head>

<body>

<p>我是唐老鸭。</p>
<p>我住在 Duckburg。</p>

<p><b>注释:</b>对于在 IE8 中工作的 :before,必须声明 DOCTYPE。</p>

</body>
</html>

2.将content的属性设置为空,把它做成 一个内容很少的盒子

<!DOCTYPE html>
<html>
<head>
<style>
p:before
{
content:"";
width:12px;
height:12px;
display:inline-block;
background-color:red;
}
</style>
</head>

<body>

<p>我是唐老鸭。</p>
<p>我住在 Duckburg。</p>

<p><b>注释:</b>对于在 IE8 中工作的 :before,必须声明 DOCTYPE。</p>

</body>
</html>

3.在元素之前或者之后插入非文本内容

插入一张图像:如下所示(图像大小按照自己的要求设置)

p:before
{
content:url(xxx.png);
}

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

p::after{
content:attr(href);
}

本博客由博主原创,如需转载需说明出处!谢谢支持!

猜你喜欢

转载自blog.csdn.net/Allenyhy/article/details/81567002
今日推荐