9

I have saved input from a textarea element to a TEXT column in MySQL. I'm using PHP to pull that data out of the database and want to display it in a p element while still showing the whitespace that the user entered (e.g. multiple spaces and newlines). I've tried a pre tag but it doesn't obey the width set in the containing div element. Other than creating a PHP function to convert spaces to &nbsp and new lines to br tags, what are my options? I'd prefer a clean HTML/CSS solution, but any input is welcome! Thanks!

2
  • What's wrong with converting spaces to and newlines to <br />? Commented Oct 1, 2008 at 0:16
  • Just personal preference - it just seems like an HTML/CSS solution makes the most sense here, as the whitespace is present in the markup when viewing source. Commented Oct 1, 2008 at 0:55

4 Answers 4

11

You can cause the text inside the pre to wrap by using the following CSS

pre {
 white-space: pre-wrap;       /* css-3 */
 white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
 white-space: -pre-wrap;      /* Opera 4-6 */
 white-space: -o-pre-wrap;    /* Opera 7 */
 word-wrap: break-word;       /* Internet Explorer 5.5+ */
}

Taken from this site

It's currently defined in CSS3 (which is not yet a finished standard) but most browsers seem to support it as per the comments.

Sign up to request clarification or add additional context in comments.

Comments

3

You could just use PHP's nl2br function.

Comments

2

You've got two competing requirements. You either want the content to fit within a certain area (ie: width: 300px), or you want to preserve the whitespace and newlines as the user entered them. You can't do both since one - by definition - interferes with the other.

Since HTML isn't whitespace aware, your only options are changing multiple spaces to "&nbsp;" and changing newlines to <br />, using a <pre> tag, or specifying the css style "white-space: pre".

Comments

1

Regarding the problem with the div, you can always make it scroll, or adjust the font down (this is even possible dynamically based on length of longest line in your server-side code).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.