Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums CSS [Solved] Best way to avoid orphaned words in headlines?

  • This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #174273
    somedirection
    Participant

    I’m investigating the best way to deal with CMS powered headlines and IF a headline would wrap, I want to ensure a headline will bring at least the last 2 words of the headline along for the ride.

    Simple example

    |------------------ wrapper width ------------|
    
    I am a long headline that fits on all one line
    
    I am a much longer headline that is just too
    long
    
    I am a much longer headline that leaves
    no orphans
    

    Hope I made a decent example of the issue

    #174280
    Senff
    Participant

    Not sure if it’s the BEST way, but I would detect the last space in a string using JavaScript and replace it with & n b s p . Like this: http://codepen.io/senff/pen/iJDKH

    Thinking about that; that will go wrong when there are spaces AFTER the last word. Perhaps it’s better to detect the last two words, and then replace the space between them.

    #174312
    __
    Participant

    If you choose to solve this server-side, the database is not the place to do it. It’s an HTML-specific issue: do it when you actually place the content in HTML.

    Here’s how you might implement @Senff’s suggestion in PHP, for example:

    <?php
    function last_s_to_nbsp( $string ){
        $string = preg_replace( '/( )(\w+)\s*$/','&nbsp;$2',$string );
        return $string;
    }
    
    //  possible usage:
    $headline = "I am a much longer headline that is just too long";
    echo "<h1>".last_s_to_nbsp( $headline )."</h1>";
    
    /* prints:
        I am a much longer headline that is just too&nbsp;long
    */
    
    #174345
    somedirection
    Participant

    Thanks guys. I don’t have access to the db layer, but I’m writing the output with Handlebars templates. The answer might be to create a helper that inserts a nbsp between the last 2 words.

    I’ll report back when I do it.

Viewing 4 posts - 1 through 4 (of 4 total)
  • The forum ‘CSS’ is closed to new topics and replies.