Home > Web Front-end > CSS Tutorial > How Can I Achieve Cross-Browser Word Wrapping in a Div Element?

How Can I Achieve Cross-Browser Word Wrapping in a Div Element?

Linda Hamilton
Release: 2024-12-07 10:16:13
Original
508 people have browsed it

How Can I Achieve Cross-Browser Word Wrapping in a Div Element?

Cross-browser Word Wrap for Extended Strings in a Div

While Internet Explorer offers its own word-wrap style, finding a cross-browser solution for wrapping text within a div is a common concern. This article explores both CSS and JavaScript methods to address this challenge.

CSS Approach

CSS provides several options for word wrapping long strings within a div:

/* Source: http://snipplr.com/view/10979/css-cross-browser-word-wrap */
.wordwrap { 
   white-space: pre-wrap;      /* CSS3 */   
   white-space: -moz-pre-wrap; /* Firefox */    
   white-space: -pre-wrap;     /* Opera <7 */   
   white-space: -o-pre-wrap;   /* Opera 7 */    
   word-wrap: break-word;      /* IE */
}
Copy after login

JavaScript Approach

Although not as elegant as CSS, JavaScript can also achieve word wrapping. One approach is to use the wordwrap function:

function wordwrap(str, width) {
  if (!width) { width = 80; }

  var re = new RegExp(".{" + width + "}(\s|$)|\S+\S{0," + (width - 1) + "}", "g");
  return str.match(re).join("\n");
}
Copy after login

Applying to a Div

To apply either approach to a div, use the appropriate code in your CSS or JavaScript file and assign the relevant class or ID to the div element.

For the CSS method:

<div class="wordwrap">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam blandit mi nibh, id sagittis tellus maximus eget. Mauris ut pharetra est, eu mattis quam.
</div>
Copy after login

For the JavaScript method:

<div>
Copy after login

The above is the detailed content of How Can I Achieve Cross-Browser Word Wrapping in a Div Element?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template