简体   繁体   中英

Displaying whitespace in HTML when pulling from MySQL TEXT column

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 ap element while still showing the whitespace that the user entered (eg 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!

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.

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".

你可以使用PHP的nl2br函数

关于div的问题,你可以随时滚动或调整字体(这甚至可以根据服务器端代码中最长行的长度动态调整)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM