Question

I'm making a responsive website for a client using twitter bootstrap, which is responsive by default. However when the words get too long in a <h1> it doesn't fit the mobile sized browser.

What I would like to do is change "thisisaverylongword" into "thisisa-verylongword" with the final part on a new line.

Is there a simple way to do this, maybe with javascript? I'm thinking some condition like "if $word is wider than $body then" or something similar. Any tips will be very useful, gold star if the same code works for any word.

Was it helpful?

Solution

You could use the (experimental) CSS property hyphens:

h1 {
  -webkit-hyphens: manual;
     -moz-hyphens: manual;
      -ms-hyphens: manual;
          hyphens: manual;
}

and specify the line break by using special unicode characters:

U+2010 (HYPHEN)

The "hard" hyphen character indicates a visible line break opportunity. Even if the line is not actually broken at that point, the hyphen is still rendered.

U+00AD (SHY)

An invisible, "soft" hyphen. This character is not rendered visibly; instead, it suggests a place where the browser might choose to break the word if necessary. In HTML, you can use ­ to insert a soft hyphen.

EDIT

As mentioned by @hustlerinc it might be needed to set word-break: break-all to make it work.

OTHER TIPS

I've written a jQuery plugin that might fit this purpose quite well. Check out ellipsis.js. Using the following configuration should work:

$('h1').ellipsis({visible: 10, more: '…', separator: '', atFront: false})

I guess the advantage of doing it this way is that the users still may display the whole header on tap if they want to.

You can apparently achieve something like this with a bit of CSS, check out the text-overflow property. Perhaps that's the ticket for this case. No JS needed. :)

Can't you set the CSS property word-break to hyphenate?

example here

I think that you must do it by yourself.

With the function "split", you split your string into a table of words. Then, you can check all the words into a for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top