这个让我有点难过。我想将我的#content div 中所有段落的第一个单词设为 14pt,而不是段落的默认值 (12pt)。有没有办法在直接的 CSS 中做到这一点,还是我把第一个单词放在一个跨度中来完成这个?
12 回答
您正在寻找的是一个不存在的伪元素。有:first-letter
和:first-line
,但没有:first-word
。
你当然可以用 JavaScript 来做到这一点。这是我发现的一些代码:http ://www.dynamicsitesolutions.com/javascript/first-word-selector/
我不得不不同意 Dale... strong 元素实际上是使用错误的元素,暗示了内容的意义、用途或重点,而您只是打算为元素提供样式。
理想情况下,您可以使用伪类和样式表来完成此操作,但由于这是不可能的,您应该使您的标记在语义上正确并使用<span class="first-word">
.
同样的事情,使用 jQuery:
$('#links a').each(function(){
var me = $(this);
me.html( me.text().replace(/(^\w+)/,'<strong>$1</strong>') );
});
或者
$('#links a').each(function(){
var me = $(this)
, t = me.text().split(' ');
me.html( '<strong>'+t.shift()+'</strong> '+t.join(' ') );
});
(通过jQuery 邮件列表中的“Wizzud” )
可悲的是,即使有了 CSS 3 之类的东西,我们仍然没有:first-word
:last-word
使用纯 CSS 的 etc 之类的东西。值得庆幸的是,现在几乎所有的东西都有一个 JavaScript,这让我接受了我的建议。使用nthEverything和jQuery,您可以扩展传统的 Pseudo 元素。
目前有效的 Pseudos 是:
:first-child
:first-of-type
:only-child
:last-child
:last-of-type
:only-of-type
:nth-child
:nth-of-type
:nth-last-child
:nth-last-of-type
并使用 nth Everything 我们可以将其扩展为:
::first-letter
::first-line
::first-word
::last-letter
::last-line
::last-word
::nth-letter
::nth-line
::nth-word
::nth-last-letter
::nth-last-line
::nth-last-word
您必须将单词包装在一个跨度中才能完成此操作。
纯 CSS 解决方案:
使用 :first-line 伪类。
display:block;
Width:40-100px; /* just enough for one word, depends on font size */
Overflow:visible; /* so longer words don't get clipped.*/
float:left; /* so it will flow with the paragraph. */
position:relative; /* for typeset adjustments. */
没有测试那个。很确定它会为你工作。我之前已经将块规则应用于伪类。对于每个第一个单词,您可能会遇到固定宽度,因此 text-align:center; 并给它一个漂亮的背景或处理负面空间的东西。
希望这对你有用。:)
-Motekye
使用强元素,这就是它的目的:
<div id="content">
<p><strong>First Word</strong> rest of paragraph.</p>
</div>
然后在您的样式表中为它创建一个样式。
#content p strong
{
font-size: 14pt;
}
这是我将一些 JavaScript 和 jQuery 放在一起用<span>
标签包装每个段落的第一个单词。
$(function() {
$('#content p').each(function() {
var text = this.innerHTML;
var firstSpaceIndex = text.indexOf(" ");
if (firstSpaceIndex > 0) {
var substrBefore = text.substring(0,firstSpaceIndex);
var substrAfter = text.substring(firstSpaceIndex, text.length)
var newText = '<span class="firstWord">' + substrBefore + '</span>' + substrAfter;
this.innerHTML = newText;
} else {
this.innerHTML = '<span class="firstWord">' + text + '</span>';
}
});
});
然后,您可以使用 CSS 为.firstWord
.
它并不完美,因为它不能解释每种类型的空白;但是,我相信它可以通过一些调整来完成您所追求的。
请记住,此代码只会在页面加载后执行,因此可能需要几秒钟才能看到效果。
没有一个简单的 CSS 方法。您可能必须使用 JavaScript + Regex 才能跨度弹出。
理想情况下,第一个单词会有一个伪元素,但你不走运,因为这似乎不起作用。我们确实有 :first-letter 和 :first-line。
您可能可以使用 :after 或 :before 的组合来获得它,而无需使用跨度。
使用 HTML+CSS 的简单方法:
TEXT A <b>text b</b>
<h1>text b</h1>
<style>
h1 { /* the css style */}
h1:before {content:"text A (p.e.first word) with different style";
display:"inline";/* the different css style */}
</style>
您可以选择第一个字母或行
p::first-letter {
font-weight: bold;
color: red;
}
在段落文本中插入跨度标记。例如
<p><span>Hello</span>My Name Is Dot</p
,然后设置第一个字母的样式。