The style of half a word, sentence, etc.

I would like to show a headline with the first three characters of a different color.

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

I would like to not break the text by inserting other elements (etc.)

A (relatively) cross-browser solution would be welcome.

+4
source share
4 answers

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

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

There is no cleaner way than you already have.

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

With CSS:

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

There :first-letter and :first-line , but not :first-word .

I suppose the reason for this is that it’s hard to pinpoint what a β€œword” is.

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

+6
source

This is not possible with the current CSS statements you are talking about nth-whatever ,

However, this can be done using JavaScript ... unless, of course, you want to go down this route, the best way to do this would be with <span> tags, since then you will not have problems with people who disabled JS.

It is entirely up to you, but if I were you, I would just make friends and use JS, this is called progressive improvement and unobtrusive JS, if the content is not destroyed, if the user disables JS, this is acceptable, see here:

http://dowebsitesneedtobeexperiencedexactlythesameineverybrowser.com/

+2
source

Unfortunately, there is no way to do this with styles. CSS3 provides us with first-letter and first-line , but not first-word and, of course, not first-n-letters .

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

JQuery implements the first-word selector, so if you are ready to go with the Javascript parameter, you can do it.

Heh. It seems that jQuery doesn't actually implement it after all. I must have used the plugin when I saw it.

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

+2
source

Source: https://habr.com/ru/post/1342303/


All Articles