CSS - 伪元素

CSS - 伪元素 首页 / CSS入门教程 / CSS - 伪元素

CSS伪元素用于向某些选项添加特殊效果,伪元素的简单语法如下-

selector:pseudo-element {property: value}

CSS类也可以与伪元素一起使用-

selector.class:pseudo-element {property: value}

最常用的伪元素如下-

Sr.No.Value & Remark
1

:first-line

p:first-line    选择每个<p> 元素的第一行

2

:first-letter

p:first-letter  选择每个<p> 元素的第一个字母

3

:before

p:before 在每个<p>元素之前插入内容

4

:after

p:after 在每个<p>元素之后插入内容

:first-line 伪元素

下面的示例演示如何使用:first-line 元素向文档中的第一行元素添加特殊效果。

<html>
   <head>
      <style type="text/css">
         p:first-line { text-decoration: underline; }
         p.noline:first-line { text-decoration: none; }
      </style>
   </head>

   <body>
      <p class="noline">
         This line would not have any underline because this belongs to nline class.
      </p>
      
      <p>
         The first line of this paragraph will be underlined as defined in the 
         CSS rule above. Rest of the lines in this paragraph will remain normal. 
         This example shows how to use :first-line pseduo element to give effect 
         to the first line of any HTML element.
      </p>
   </body>
</html>

它将产生以下效果-

:first-letter 伪元素

下面的示例演示如何使用:first-letter 元素向文档中的元素的首字母添加特殊效果。

<html>
   <head>
      <style type="text/css">
         p:first-letter { font-size: 5em; }
         p.normal:first-letter { font-size: 10px; }
      </style>
   </head>

   <body>
      <p class="normal">
         First character of this paragraph will be normal and will have font size 10 px;
      </p>
      
      <p>
         The first character of this paragraph will be 5em big as defined in the 
         CSS rule above. Rest of the characters in this paragraph will remain 
         normal. This example shows how to use :first-letter pseduo element 
         to give effect to the first characters  of any HTML element.
      </p>
   </body>
</html>

它将产生以下效果-

:before 伪元素

下面的示例演示如何使用:before 元素在任何元素之前添加一些内容。

<html>
   <head>
      <style type="text/css">
         p:before {
            content: url(/images/bullet.gif)
         }
      </style>
   </head>

   <body>
      <p> This line will be preceded by a bullet.</p>
      <p> This line will be preceded by a bullet.</p>
      <p> This line will be preceded by a bullet.</p>
   </body>
</html>

它将产生以下效果-

:after 伪元素

下面的示例演示如何使用:after 元素在任何元素之后添加一些内容。

<html>
   <head>
      <style type="text/css">
         p:after {
            content: url(/images/bullet.gif)
         }
      </style>
   </head>

   <body>
      <p> This line will be succeeded by a bullet.</p>
      <p> This line will be succeeded by a bullet.</p>
      <p> This line will be succeeded by a bullet.</p>
   </body>
</html>

它将产生以下效果-

无涯教程网

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

程序员的数学基础课 -〔黄申〕

Vue开发实战 -〔唐金州〕

零基础学Java -〔臧萌〕

MongoDB高手课 -〔唐建法(TJ)〕

Serverless入门课 -〔蒲松洋(秦粤)〕

Selenium自动化测试实战 -〔郭宏志〕

技术管理案例课 -〔许健〕

跟着高手学复盘 -〔张鹏〕

LangChain 实战课 -〔黄佳〕

好记忆不如烂笔头。留下您的足迹吧 :)