如何将CSS应用到第一个字母后:内容之前?

时间:2012-07-29 14:42:20

标签: css pseudo-element

<!DOCTYPE html>
<html lang="en">
<head>
<style type="text/css">
p:before {  
    content:"Former - "; 
    color:red;
    font-family:"Tahoma" ,Times New Roman;
    font-size:70%;
}

p.normal:first-letter {
    font-size:40px;
    color:blue;
}
</style>
</head>
<body>
  <p class="normal">First character of this paragraph will
  be normal and will have font size 40px;</p>
</body>
</html>

这里,:before伪元素中的内容显示为红色,但我也希望设置“ F 本段第一个字符”的字符“F”的样式蓝色。但相反,我看到“ F ormer - ”的“F”为蓝色。

我想要的是在:before内容之后.normal:before 的第一个字母同时应用于同一段落。这可能吗?如果是这样,怎么样?

4 个答案:

答案 0 :(得分:6)

通常情况下,您会使用:first-letter伪元素执行此操作,但看到:before内容为inserts text before the actual content of your paragraph,而不是实际内容的第一个字母,{ {1}}会匹配:first-letter内容的第一个字母。

这意味着代替:

:before

你真的得到了这个:

<p class="normal">
  <p:before>Former - </p:before>
  <p.normal:first-letter>F</p.normal:first-letter>irst character of this paragraph will
  be normal and will have font size 40px;
</p>

由于CSS生成内容的工作方式,我认为只有在插入内容之前,纯CSS中的解决方案才能到达实际内容的第一个字母。

作为替代方案,您可以使用<p class="normal"> <p:before> <p.normal:first-letter>F</p.normal:first-letter>ormer - </p:before> First character of this paragraph will be normal and will have font size 40px; </p> 代替span伪元素,然后可以应用蓝色,但这意味着您必须插入额外的元素:< / p>

:first-letter
  <p class="normal"><span>F</span>irst character of this paragraph will
  be normal and will have font size 40px;</p>

答案 1 :(得分:1)

?你好。

例如,如果您无法在没有JavaScript的情况下编辑HTML,则可以使用纯CSS,只要您对“块级”元素的:before或:after进行样式设置即可。

p:before {
  content: 'Wisdom'
}

p:first-letter {
  font-size: 7vw;
}
<p></p>

?请注意?:: first-letter CSS伪元素将样式应用于块级元素的第一行的首字母,但仅在不带有其他内容(例如图像或内联表)的情况下才使用

?出处:https://developer.mozilla.org/en-US/docs/Web/CSS/::first-letter

✌干杯, ?肖恩(Sean Sr。)

答案 2 :(得分:0)

将 :before 更改为 :after,并按照 user719662 的建议使用绝对定位

p:after {  
  position: absolute;
left: 0;
content:"Former - "; 
color:red;
font-family:"Tahoma" ,Times New Roman;
font-size:70%;
}

p.normal:first-letter {
  font-size:40px;
color:blue;
}

答案 3 :(得分:-1)

<!DOCTYPE html>
<html lang="en">
  <head>

    <title>Complicated pseudo element and span</title>

    <style type="text/css">
      <!--
      p:before {  
           content:"Read this -"; 
           color:red;
           font-family:"Tahoma" ,Times New Roman;
           font-size:100%;}

            .span {
                   font-size:40px;
              color:blue; 
                 } 

         -->
   </style>

  </head>
  <body>

    <p><span style="color:blue; font-size:30px" >F</span>irst character of this paragraph
        will be normal and will have font size 40px;</p>

  </body>
</html>

感谢您的指导 - 我按照我想象的方式获得了输出