Sahat Yalkabov
Sahat Yalkabov

Reputation: 33624

How to apply CSS to second word in a string?

If I have the following string: John Smith, how could I use CSS to set font-weight: bold on the second word in order to achieve: John Smith.

Can this be done in pure CSS?

Update: I am retrieving user's name from the server, so in my template it is #{user.profile.name}.

Upvotes: 6

Views: 14563

Answers (3)

Puka
Puka

Reputation: 1575

It seems to be impossible by using only pure CSS. However, with a bit of JS you could get there pretty easily:

const phrases = document.querySelectorAll('.bold-second-word');
for (const phrase of phrases) {
  const words = phrase.innerHTML.split(' ');
  words[1] = `<b>${words[1]}</b>`; // this would return the second word
  phrase.innerHTML = words.join(' ');
}
<p class="bold-second-word">John Smith</p>
<p class="bold-second-word">Aaron Kelly Jones</p>

Upvotes: 1

m59
m59

Reputation: 43745

Since a js solution was suggested and pure CSS isn't presently possible: Live demo (click).

Sample markup:

<p class="bold-second-word">John Smith</p>
<p class="bold-second-word">This guy and stuff.</p>

JavaScript:

var toBold = document.getElementsByClassName('bold-second-word');
for (var i=0; i<toBold.length; ++i) {
  boldSecondWord(toBold[i]);
}

function boldSecondWord(elem) {
  elem.innerHTML = elem.textContent.replace(/\w+ (\w+)/, function(s, c) {
    return s.replace(c, '<b>'+c+'</b>');
  });
}

Upvotes: 4

rvighne
rvighne

Reputation: 21887

It cannot be done in pure CSS, sorry. But if you are willing to accept a JavaScript fix, then you might want to look into something like this:

  • Find the start and end index of the second word in the element's textContent.
  • Add contenteditable attribute to element.
  • Use the Selection API to select that range.
  • Use execCommand with the bold command.
  • Remove contenteditable attribute.

EDIT: (just saw your edit) I agree this is a bit too hack-y for most uses. Perhaps you'd be better off saving what the last name is as meta-data?

Upvotes: 1

Related Questions