Style half of a word, sentence, etc

强颜欢笑 提交于 2020-01-03 17:32:24

问题


I'd like to show a title with the first three characters in different color.

I know this can be done with <h2><span>The</span> awsome title</h2> but I was wondering if there is some kind of "nth-child" property that can be applied to characters inside an element.

I'd like to avoid breaking the text by inserting other elements ( etc.)

A (relatively) crossbrowser solution would be welcome.


回答1:


Yep, JavaScript is the only way I can think of (as everyone else has already said!). Demo here.

$(function() {
    $('h2').each(function(){
        $(this).html( $(this).text().replace(/(^\w{3})/,'<span>$1</span>'));
    });
});



回答2:


There is no cleaner way than what you already have.

<h2><span>The</span> awesome title</h2>

With CSS:

h2 {
    color: red
}
h2 span {
    color: blue
}

There's :first-letter and :first-line, but no :first-word.

I imagine the reason for this is that it's hard to define exactly what a "word" should be.

The only way to do it without changing your markup is to use JavaScript to enclose the first word with a <span> (and style it the same way), but I would only recommend that if the rest of your site already heavily relies on JavaScript to function.




回答3:


This isn't possible with the current CSS operators you are talking about nth-whatever,

This could however be done with JavaScript... if of course you want to go down that route, the best way to do it would be with <span> tags as then you will have no problems with people who have disabled JS.

It is entirely up to you, but if I were in your position I would just man up and use JS, it is called progressive enhancement and unobtrusive JS, as long as the content is not wrecked if the user disables JS it is acceptable, see here:

http://dowebsitesneedtobeexperiencedexactlythesameineverybrowser.com/




回答4:


Sadly, there isn't a way to do this with stylesheets. CSS3 provides us with first-letter and first-line, but not first-word, and certainly not first-n-letters.

See also the answers to this question for more: CSS to increase size of first word

JQuery does implement a first-word selector, so if you're prepared to go with the Javascript option, you may be able to do it.

Heh. It seems that JQuery doesn't actually implement it after all. I must have been using a plugin when I saw it.

But here's a link to a Javascript solution that might help: http://www.dynamicsitesolutions.com/javascript/first-word-selector/



来源:https://stackoverflow.com/questions/5195663/style-half-of-a-word-sentence-etc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!