nick501414
nick501414

Reputation: 129

Can you use CSS to select and style a string inside a paragraph(s)?

is it possible to pick out and style a particular word in a paragraph using just css? So for example in the sentence "hello my name is nick, hello to you all", would it be possible to target the word "hello" wherever it appears and to add a rule, such as changing the color of hello anytime it appears? I don't want to have to add a span tag around every hello that appears.

I would like to do this in only css if possible. css3 is fine to use.

Upvotes: 1

Views: 3303

Answers (6)

bfavaretto
bfavaretto

Reputation: 71908

For fine control over any particular word, or fragment, you'd have to wrap it into a span and style the span, as others said.

However, there are also the :first-line and :first-letter pseudo-elements, available since CSS2. So, for example, you can have the first letter have a different font-size, and the whole first line have a different color, like this:

p:first-letter {font-size: 30px;}
p:first-line {color: #FF0000;}

Upvotes: 1

Christoph
Christoph

Reputation: 51181

CSS has 2* Pseudo-Elements:

::first-line and ::first-letter. These are the only possibilities to target only a part of the innerhtml of a Tag.

(*ofc it has more, i mean for the purpose of selecting only a part of the innerhtml.)

Upvotes: 2

stallion
stallion

Reputation: 11

If you know the contents of the para and have patience you can wrap each of those words that you need to highlight in a span tag. Assign them the same class and then style it.

Upvotes: 1

pollirrata
pollirrata

Reputation: 5286

CSS selectors work on tags or pseudo clases, not querying your text. Check the reference http://www.w3.org/TR/selectors/, maybe you can find something useful here.

Upvotes: 0

Simon Edström
Simon Edström

Reputation: 6619

What I know its not possible to target textnode, you can do it by using Javascript. Wrap the Hello word with a span tag and set the properties to the SPAN tag

Upvotes: 0

Dave
Dave

Reputation: 29121

No, you'd need to use javascript for that. Or, if you're using PHP/ASP...etc, you could add spans around any designated word(s) automatically before the page renders.

Upvotes: 1

Related Questions