CSS:首字母不起作用


76

我正在尝试将CS​​S样式应用于从Microsoft Word文档生成的一些HTML代码段。Word生成的HTML相当糟糕,并且包含许多内联样式。它是这样的:

<html>
    <head></head>
    <body>
        <center>
            <p class=MsoNormal><b style='mso-bidi-font-weight:normal'><span
               style='font-size:12.0pt;line-height:115%;font-family:"Times New Roman"'>Title text goes here<o:p></o:p></span></b></p>

            <p class=MsoNormal style='margin-left:18.0pt;line-height:150%'><span
                style='font-size:12.0pt;line-height:150%;font-family:"Times New Roman"'>Content text goes here.<o:p></o:p></span></p>
    </body>
</html>

...非常简单,我想为标题部分的第一个字母设置样式。它只需要更大并且使用不同的字体即可。为此,我尝试使用:first-letter选择器,例如:

p b span:first-letter {
    font-size: 500px !important;
}

但这似乎不起作用。这是一个小提琴,说明了这一点:

http://jsfiddle.net/KvGr2/

任何想法有什么问题/如何正确设置标题部分的首字母?我可以对标记进行一些细微的更改(例如在事物周围添加包装器div),尽管并非没有困难。

Answers:


199

::first-letter不适用于内联元素(例如)span::first-letter适用于元素,例如段落,表标题,表单元格,列表项或display属性设置为的元素inline-block

因此,最好使用::first-letterap而不是a span

p::first-letter {font-size: 500px;}

或者,如果您想要一个::first-letter选择器,span则可以这样编写:

p b span::first-letter {font-size: 500px !important;}
span {display:block}

MDN为这种非显而易见的行为提供了理由

::first-letterCSS伪元素选择一个块的第一行的第一个字母,如果它不是通过在其线的任何其他内容(例如图像或内联表)之前。

...

第一条线仅意在块容器箱,因此,::first-letter伪元素仅具有一个上的元件效果display的值blockinline-blocktable-celllist-itemtable-caption。在所有其他情况下,::first-letter均无效。

另一个奇怪的情况(除了不能处理内联项目)是,如果您使用:before:first-letter将应用于而不是实际的第一个字母,请参见codepen

例子

参考文献

https://developer.mozilla.org/zh-CN/docs/Web/CSS/::first-letter http://reference.sitepoint.com/css/pseudoelement-firstletter


谢谢你 我注意到了一件奇怪的事-%符号也被调整了大小?jsfiddle.net/iamkeir/KvGr2/76
iamkeir 2013年

2
+1感谢您为我省去更多的麻烦。我必须认为使用span元素非常普遍,因此令我惊讶的是它不起作用。
Yuck

14

您可以通过将span的display属性设置为inline-block来获得预期的行为:

.heading span {
  display: inline-block;
}

.heading span:first-letter {
  color: red;
}
<div class="heading">
  <span>An</span>
  <span>Interesting</span>
  <span>Heading</span>
</div>


如果我的文字以符号开头,该怎么办。<div>!会话已过期</ div>
gauti,

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.