Search code examples
htmlcssword-break

Fit text in container without breaking word using HTML/CSS only


On my webpage I've used fancybox for preview section of description text in popup. Text shows perfectly fine on desktop but on popup it shows something like this.

Please note that the descriptive text I'm getting for the display it include   for each space user gives for the sentence after each word.

enter image description here

and when I use word-break: break-all; it gets like this

enter image description here

then I've used word-break:break-word; also and get this

enter image description here enter image description here

you can spot the difference now, that it breaks word viz clearly not acceptable. I want to break sentences meaningfully not the word!

Problem is I can only use HTML/CSS only here for fixing this, have looked many que/ans here but no luck.

Please help me into this.

I've created a JSFiddle please look into this may be this will help to understand clearly.


Solution

  • Note: If you don't want to modified server side scripts, you can use this JavaScript solution instead. I don't think you can do so with CSS only without doing any amendments in your server side code to remove these &nbps;.

    In that case, you should first decode HTML special chars to simple text using following JavaScript code.

    var text = $("<textarea/>").html('your HTML encoded text here with &nbsp; and all').text();
    $('your viewing div/p selector').html(text);
    

    And add this CSS property in your viewing div or p.

    white-space: pre-wrap;
    

    It should work.