word-wrap: break-word; repair or substitute

Is there a way to prevent line breaks before words that are going to break anyway when using word-wrap: break-word;? It seems unnecessary and unattractive. Any suggestions?

For Example:

Consider a div with word-wrap: break-word;, set at a width equal to 23 "x" characters like this:

xxxxxxxxxxxxxxxxxxxxxxx


The innerHTML of the div is "xx xxxxxxxxxxxxxxxxxxxxxxxxxxxx" as follows:

<div>xx xxxxxxxxxxxxxxxxxxxxxxxxxxxx</div>   


This demonstrates how the innerHTML of the div is presented compared to the desired display within a 23 "x" width.

Current Output:
xx
xxxxxxxxxxxxxxxxxxxxxxx
xxxxx

Desired Output:
xx xxxxxxxxxxxxxxxxxxxxx
xxxxxxxx



Using word-break: break-all; or similar attributes does not solve the issue. I want words that fit within the container width to remain intact without breaking, while only allowing words wider than the container width to break without an initial line break like with word-wrap: break-word; which is both superfluous and unsightly.

Answer №1

Adding on to MaxiGui's response, another option is to incorporate non-breaking spaces &nbsp; in your HTML code (or replace regular spaces with non-breaking spaces using JavaScript). However, I personally believe that utilizing word-break: break-all; is a more effective approach.

UPDATE: Hyphens can handle everything effectively https://developer.mozilla.org/en-US/docs/Web/CSS/hyphens

Answer №2

As mentioned by @Sfili_81

something similar to word-break: break-all;

Here is the solution:

const text = document.getElementById("demo").innerHTML;

const dataArray = text.split(' ');

const paragraph = document.getElementById("demo");
let finalText = "";
for (let j = 0; j < dataArray.length; j++){
    if (dataArray[j].length > 6 ) {
      finalText = finalText + " <span>"+ dataArray[j]+"</span>"; 
  }
  else{
    finalText = finalText + " " + dataArray[j];
  }
}

paragraph.innerHTML = finalText;
div{
  width:50px;
  background: red;
 
}
span{
  word-break:break-all;
}
<div id="demo">test teeeeeeeeeeest test test test</div>

PS: The question has been flagged as a duplicate of: How to force a line break in a long word in a DIV?

EDIT

Since both `break-all` and `break-word` have limitations, the only solution is Javascript. In this example, we are adding span elements to words with a length over 6 characters.

Answer №3

Here is an alternative approach using jQuery:

Below is the HTML code snippet:

<div id="demo">xx xxx xxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxx</div>

JS code snippet:

$(document).ready(function() {
  var words = $('#demo').text().split(' ');
  $('#demo').empty();
  $.each(words, function(i, v) {
    $('#demo').append($('<span>').text(v));
  })
});

CSS styles:

#demo {
  width: 100px;
  border: 1px solid #F00;
  word-wrap: wrap;
  word-break: break-all;
}

#demo span {
  display: inline-block;
  border: 1px dashed #00F;
  word-wrap: break-word;
  margin-right: 2px; /* adding space back */
}

This method offers a slight improvement over the original solution by eliminating the need for a hardcoded word length.

Check out the JSFiddle demo here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can HTML Elements be used within a Contenteditable section?

I am facing an issue with a contenteditable tag on my website. Users are unable to type code into the tag and have it display as an actual element instead of just text. Is there a way for users to input full, working HTML elements in a contenteditable box ...

The jQuery method .on gathers and retains click events

I created a component that manages a view containing articles with games. In order to prevent memory overload and optimize performance, I implemented a solution where when a user clicks on an article (each having the class "flashgame"), they can choose to ...

Steps for accessing the value from an input tag within the same form:

Exploring how to utilize the value "typed_from_user" in another tag within the same form, using only PHP & HTML without relying on JavaScript. Is this scenario feasible? For instance, let's say I wish to reuse the term 'pizza' <form> ...

Making sure Angular picks up on $scope changes

Currently, I am in the process of developing my inaugural AngularJS application and am faced with the challenge of a directive not updating its view when there are changes to the array received from the service. Below is the structure of my directive: an ...

The entry '0-0' already exists for the key 'local_part', please enter a unique value

Creating a simple API to handle GET, POST, DELETE, and UPDATE requests. The GET method is functioning correctly, but encountering an issue with the POST method. When attempting to post data, an error is being encountered: error: Error: ER_DUP_ENTRY: ...

"Create a table with rows that automatically adjust to the same height, regardless

Is there a way to create a table where the height remains constant regardless of the number of rows added? For example: https://i.sstatic.net/zJNqD.png Even if rows are added, I want the height to stay consistent. I cannot use percentage since the numb ...

Contrasting the utilization of Angular $scope dependency with independent usage

As I delve into Angular, there's something that puzzles me. Being a newcomer to Angular, I recall a tutorial where they employed this syntax for applying properties to a controller's scope: app.controller('someCtrl', function(){ ...

How can I customize the appearance of tab buttons in a QtabWidget using PySide?

Looking for a way to customize the tab buttons on a QtabWidget in PySide. I've managed to style other elements of my custom widget, but can't figure out how to style the QtabWidget tabs. My attempt: self.tabWidget = QtGui.QtabWidget(Form) self. ...

[webpack]: npm ERROR! Call stack size limitation exceeded

While trying to install webpack using npm i -D webpack, an error is encountered as shown below. npm ERR! Maximum call stack size exceeded npm ERR! A complete log of this run can be found in: npm ERR! /Users/shobhuiy1/.npm/_logs/2019-02-05T10_31_29_46 ...

trouble encountered while parsing JSON information using JavaScript

[ [ { "Id": 1234, "PersonId": 1, "Message": "hiii", "Image": "5_201309091104109.jpg", "Likes": 7, "Status": 1, "OtherId": 3, "Friends": 0 } ], [ { "Id": 201309091100159, "PersonI ...

When integrating react-router 5 and redux 7, there is an issue where the state is not being reset when navigating to a new route using react-router's <Link

My current setup includes the following versions: `"react-router": "^5.2.0",` `"react-router-domreact-router": "^5.2.0",` I'm unsure if my setup is compatible with React-router 5 as I was using a version prior ...

Is there a way to execute .jsx Photoshop scripts on images using Java?

Currently, I am in the process of developing a Java program to apply edits to a sequence of images. However, I am searching for a simple and adaptable method to conduct these edits by utilizing Image Editors Scripts (such as Photoshop Scripts, Gimp Scripts ...

Activate audio and trigger notification

I'm looking to incorporate a small beep sound into my web application before displaying an alert message. Here's what I currently have: if(_none_valid) { $.playSound('/static/wav/beep_error.wav').delay(300); alert('ERROR: ...

When I submit a form with an empty date input field, the Datepicker is sending a 0000-00-00 date

[I am experiencing an issue with my date input field. When I submit without entering any value, the date on the view page shows as 0000-00-00 instead of being empty or blank.] <div class="col-sm-3 col-sm-offset-1"> <div class="input-group"& ...

Python makes sure that HTML values remain constant even after a button is clicked by Selenium

I am currently utilizing Soup and Selenium to access a particular page . My objective is to extract a comprehensive list of pricing and ratings for different types of packaging available on this webpage. https://i.sstatic.net/3gbJ7.png Displayed below is ...

Resizing images using a dynamic frame size

I am in need of some assistance as I am currently facing a roadblock. My goal is to develop a picture framing tool for photos where users can specify the size of their photo, choose a colored cardboard mount, and select a frame type. My client has requeste ...

Storing div content in database directly

I have a straightforward div that allows users to edit content on the page. I need to save this content in a database, but without including any HTML tags while still preserving line breaks. Currently, I am using the innerText property for this purpose. N ...

Navigating JSON within HTML forms

I'm reaching out because I have been using a workaround that seems to be effective, but I am concerned about potential issues down the line. To create an HTML form in PHP, I am using SimpleXML and DOM to manage the source code (an HTML file containin ...

Tailwind custom classes are not being rendered on mobile devices and Chrome DevTools, however, they are functioning properly on desktops and Safari DevTools

During the development of my project using Tailwind CSS, I focused on desktop compatibility and ensured responsiveness with Safari and Google Chrome. However, upon switching to DevTools, I encountered issues that persisted when testing on mobile devices. ...

Is it possible to implement a custom radio tab index without using JavaScript

Is it possible to apply the tabindex attribute on custom radio buttons, hide the actual input element, and use keyboard shortcuts like Tab, Arrow Up, and Arrow Down to change the value? Check out this example on StackBlitz ...