CSS: 第一个字母不起作用

我正在尝试将 CSS 样式应用于从 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) ,但这并非没有困难。

73314 次浏览

::first-letter does not work on inline elements such as a span. ::first-letter works on block elements such as a paragraph, table caption, table cell, list item, or those with their display property set to inline-block.

Therefore it's better to apply ::first-letter to a p instead of a span.

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

or if you want a ::first-letter selector in a span then write it like this:

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

MDN provides the rationale for this non-obvious behaviour:

The ::first-letter CSS pseudo-element selects the first letter of the first line of a block, if it is not preceded by any other content (such as images or inline tables) on its line.

...

A first line has only meaning in a block-container box, therefore the ::first-letter pseudo-element has only an effect on elements with a display value of block, inline-block, table-cell, list-item or table-caption. In all other cases, ::first-letter has no effect.

Another odd case(apart from not working on inline items) is if you use :before the :first-letter will apply to the before not the actual first letter see codepen

Examples

References

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

This is because :first-letter only operates on block / inline-block elements. SPAN is an inline element.

Taken from http://reference.sitepoint.com/css/pseudoelement-firstletter:

The :first-letter pseudo-element is mainly used for creating common typographical effects like drop caps. This pseudo-element represents the first character of the first formatted line of text in a block-level element, an inline block, a table caption, a table cell, or a list item.

You can get the intended behavior by setting the span's display property to 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>