bold the first word of the HTML paragraph

Asked

Viewed 261 times

2

I wanted to know how to put the first word of a paragraph in bold. I am using the file reset.css. I have tried to use <b> </b> and also <Strong> </Strong> but nothing happens. I also tried to use font-Weight: Bold; however in this case it leaves the whole paragraph in bold and I would just like to leave a word

2 answers

4

by CSS the options closer than you want are the selectors :first-Letter (first letter) and :first-line (first line), for your case I believe only surrounding the first word manually/programmatically with a tag (such as Strong):

<p><strong>Primeira</strong> palavra em negrito</p>

JS code example to split first word from the rest of the text:

var texto = "Primeira palavra em negrito";
var ispace = texto.indexOf(' ');
if (ispace >= 0) texto = [texto.substr(0,ispace),texto.substr(ispace)];
else texto = [texto];
//texto = ["Primeira", " palavra em negrito"]

1

That answer is just one workaround with CSS for fun :)

It has a well-placed gambit that you can only do with CSS, it’s even elegant, but it has a point against, if you select the text the first word looks like it was not celecionada, but if you give a Ctrl+C will pick up the right text...

What I did was pass the same name from the first word to an attribute data right in the tag, and in CSS I used a pseudo elemento to bold. I don’t know if it will save you a lot of time, but it can help you...

//esse script é só para vc ver como fica o elemento e o texto dele no DOM

var p = document.querySelectorAll('p')

console.log(p[0],'\n',p[1]);
p {
  position: relative;
}
p::before {
  content: attr(data-bold);
  font-weight: bold;
  text-transform: capitalize;
  display: inline-block;
  position: absolute;
  background-color: #fff;
  top: 0;
  left: 0;
}
<p data-bold="negrito">Negrito lorem ipsum dolor!</p>

<p data-bold="rapaz!">Rapaz! Que doidera</p>

  • and that "gambeta", this will do something like create a DIV covering the text below, depending on the fonts used, the Bold version, may end up occupying more space than normal and swallow a little beyond the first word ... '-'

  • @Anon yes is vdd rss, well noted, it can happen mainly in more oblique fonts, and tbm wouldn’t work if the text is on an image, the background has to be smooth

Browser other questions tagged

You are not signed in. Login or sign up in order to post.