CSS伪元素

CSS伪元素

  • :first-line;

  • :first-letter

  • :before

  • :after


:first-line 伪元素

  • "first-line" 伪元素用于向文本的首行设置特殊样式。

<html>
<head>
<style type="text/css">
p:first-line 
{
color: #ff0000;
font-variant: small-caps
}
</style>
</head>
<body>
<p>
浏览器会根据 "first-line" 伪元素中的样式对 p 元素的第一行文本进行格式化:第一行文字设置样式为红色,第二行为默认样式
</p>
</body>
</html>

注释:"first-line" 伪元素只能用于块级元素。

注释:下面的属性可应用于 "first-line" 伪元素:

  • font
  • color
  • background
  • word-spacing
  • letter-spacing
  • text-decoration
  • vertical-align
  • text-transform
  • line-height
  • clear

:first-letter 伪元素

  • "first-letter" 伪元素用于向文本的首字母设置特殊样式:

<html>
<head>
<style type="text/css">
p:first-letter 
{
color: #ff0000;
font-size:xx-large
}
</style>
</head>
<body>
<p>
第一个文字设置样式
</p>
</body>
</html>

注释:"first-letter" 伪元素只能用于块级元素。

注释:下面的属性可应用于 "first-letter" 伪元素:

  • font
  • color
  • background
  • margin
  • padding
  • border
  • text-decoration
  • vertical-align (仅当 float 为 none 时)
  • text-transform
  • line-height
  • float
  • clear

:before 伪元素

  • ":before" 伪元素可以在元素的内容前面插入新内容

<html>
<head>
<style type="text/css">
h1:before {content:"///////";
           color:red;
           font-size:small;}
</style>
</head>
<body>
<h1>This is a heading</h1>
</body>
</html>

:after 伪元素

  • ":after" 伪元素可以在元素的内容之后插入新内容。

<html>
<head>
<style type="text/css">
h1:after {content:".......";
           color:red;
           font-size:small;}
</style>
</head>
<body>
<h1>This is a heading</h1>
</body>
</html>

伪元素与 CSS 类

  • 伪元素可以与 CSS 类配合使用:

<html>
<head>
<style type="text/css">
p.article:first-letter{color: red;}
</style>
</head>
<body>
<p class="article">This is a paragraph in an article。</p>
</body>
</html>

多重伪元素

  • 可以结合多个伪元素来使用。

<html>
<head>
<style type="text/css">
p.article:first-line{color: blue;}
p.article:first-letter{color: red;}
p.article:after
  {
  content:".....";
  font-size:xx-large;
  }
</style>
</head>
<body>
<p class="article">This is a paragraph in an article。</p>
</body>
</html>
  • :first-letter与:before混合使用时:first-letter会失效

<html>
<head>
<style type="text/css">
p.article:first-line{color: blue;}
p.article:first-letter{color: red;}
p.article:before
  {
  content:"/////";
  font-size:xx-large;
  }
</style>
</head>
<body>
<p class="article">This is a paragraph in an article。</p>
</body>
</html>
原文地址:https://www.cnblogs.com/wen-qing/p/13515070.html