Ian Gallant Ian Gallant - 24 days ago 12
CSS Question

<p> tag putting all text on one line when line breaks exist

Basically I have a webpage that is displaying a description for a client of a case.

What is happening is this description then gets displayed within a paragraph tag but it is placing everything on one line. Normally this occurs when you have a paragraph tag but the string is too long and it overflows, but this isn't the case here.

Example.

This is how the description shows in the webpage.

Description

hjkhjkhj sfgsdfgsdfghjkfjkfghjfghjfgh hjkgh jhkfghjkghjkgh jhkghjkg fjghjfghjfghjfghj fghdfhd fghfgdhfghdfghd x x x ^^^^^^


When I go into the DOM explorer and look at the tag itself this is what it shows me.

<p>hjkhjkhj


sfgsdfgsdfghjkfjkfghjfghjfgh

hjkgh
jhkfghjkghjkgh
jhkghjkg
fjghjfghjfghjfghj

fghdfhd


fghfgdhfghdfghd

&nbsp;x&nbsp;
x&nbsp;x&nbsp;





^^^^^^</p>


It is showing the line breaks where they are supposed to occur, but this doesn't translate to the webpage itself.

Just wondering if anyone has come across this before? Or if anyone knows some CSS that will get around this problem.

Answer

HTML "collapses" successive whitespace characters, and more importantly, it treats literal "line break characters" as just plain whitespace:

A line break is defined to be a carriage return (&#x000D;), a line feed (&#x000A;), or a carriage return/line feed pair. All line breaks constitute white space.

(source)


In this example, even though we have multiple carriage returns between "hello" and "world," it still treats it as just one whitespace character.

<p>
  Hello
  
  
  
  World
</p>


In this example, we have no whitespace between "hello" and "world," but because we introduce the line break element <br>, we do introduce a true line break.

<p>
  Hello<br>World
</p>


As others have mentioned, if you would like to maintain the whitespace without introducing <br> elements, you can use CSS to preformat your paragraph tag. Namely, use the white-space attribute (source) and change its value to pre-wrap.

p {
  white-space: pre-wrap;
}
<p>
  Whitespace here
  
  is      maintained!
</p>

Comments