Replacing <br>
Elements with Commas
A site I was working on had an address, e.g.
3955 Conference Center Way
Sylvania
AL 35988
marked up as
<p class="address">
3955 Conference Center Way<br />
Sylvania<br />
AL 35988
</p>
As a quick side note, <address>
should only be used when referring to the contact details of an article or a page, not for arbitrary addresses.
Anyway, for wider screens, we wanted to display it on one line:
3955 Conference Center Way, Sylvania, AL 35988
with commas inbetween what used to be each line. Is there a way to do that? It’s possible to hide <br>
elements with display: none;
, which prevents them from causing a line break, but it doesn’t let us introduce a comma in its place.
On blink- and webkit-browsers, there is actually a rather simple solution:
@media (min-width: 40em) {
br {
content: '';
}
br:before {
content: ', '
}
}
The first rule removes the line break, and the second introduces the comma in its place. Done.
Except we’re not. <br>
is a replaced element, which means its representation is outside the scope of CSS, and the interaction of :before
and :after
with replaced elements is undefined. As such, Firefox and Internet Explorer don’t behave in the same way, and the line breaks persist.
However, it might be possible to go the other way: how about using an empty <span>
and making it behave like a <br>
?
<address>
3955 Conference Center Way<span class="br"></span>
Sylvania<span class="br"></span>
AL 35988
</address>
.br:before {
content: '\A';
white-space: pre-line;
}
\A
or \000A
is the unicode character for a line feed, and white-space: pre-line;
is to get it to be printed literally rather than just collapsed like usual whitespace.
If we want it to display a comma instead of a line break at certain sizes, we could write, for example:
@media (min-width: 40em) {
.br:before {
content: ','
}
}
And there it is: an element that can behave like a line break at some sizes, and a comma at others.