Home > OS >  Replaced BR tag with a comma but adds a space after text
Replaced BR tag with a comma but adds a space after text

Time:06-19

I noticed that a space is added when I replace BR tag with a comma in the text:

HTML:

<div>
one first
<br >
two second
<br >
three third
</div>

CSS:

.hey {
  content: '';
}
.hey:before {
  content: ', ';
}

Result: one first , two second , three third

The result I want: one first, two second, three third

JSFiddle: https://jsfiddle.net/tk4f7n9b/

PS: I can only use CSS. I can't inject or change any code into HTML. I can add an external JS file though.

CodePudding user response:

The reason why there is a space, is because there are new lines between elements. What you can do is use negative left margin:

.hey {
  content: '';
}
.hey:before {
  content: ',';
  margin-left: -0.2em;
}
<div>
one first
<br >
two second
<br >
three third
</div>

CodePudding user response:

@vanovm's answer is a good CSS only solution. Using an external JS file: change the <br> elements to be on the same line as the text nodes.

let el = document.querySelector('div')

el.innerHTML = `<div>
one first<br >
two second<br >
three third
</div>`
.hey {
  content: '';
}
.hey:before {
  content: ', ';
}
<div>
one first
<br >
two second
<br >
three third
</div>

  • Related