Wrap title

A way to get aleading title to wrap in a nice way using JS

by brendanarnold

HTML

<div id="title-container">
    <div id="leading-title">
        Some text making the main title
    </div>
    <div id="following-title">
        following text usually a bit longer
    </div>

</div>


<p>&larr; resize this bar to see the wrapping behaviour</p>

CSS

/* Define the page font size */
html {
    font-size: 16px;
}

/* Define how big 1em is for the children of body */ 
body {
    font-size: 100%;
}

#title-container {
    background: red;
    overflow: auto;
    width: 100%;
    position: relative;   
}

#leading-title {
    float: left;
    background: green;
    font-size: 2.4em;
}

#following-title {
    float: left;
    background: blue;
    font-size: 1.4em;
    position: absolute;
    bottom: 0px;
    /* Needs to be hidden to begin with otherwise 
    is seen to jump around screen */
    visibility: hidden;
}

JavaScript

$(document).ready(function() {
    
    function placeFollowTitle() {
        var BASELINE_ADJUST_PX = 5; // Correct for different baseline with smaller text
        var titleContainer = $("#title-container");
        var followTitle = $("#following-title");
        var leadingTitle = $("#leading-title");
        // Scenarios
        // 1. Both can fit in the width
        // 2. Only One can fit in width
        if (followTitle.width() + leadingTitle.width() 
            >= titleContainer.width()) {
            // Is too big for one line, wrap to next
            followTitle.css({
                "position" : "relative",
                "bottom" : "0px",
                "left" : "0px",
                "visibility" : "visible",
            });
        } else {
            // Will both fit on same line
            followTitle.css({ 
                "left" : leadingTitle.width() + "px", 
                "position" : "absolute",
                "bottom" : BASELINE_ADJUST_PX + "px",
                "visibility" : "visible",
            });
            console.log("lt");
        }
    }
    
    // Run when window is resized and once when document loaded    
    $(window).resize(placeFollowTitle);
    placeFollowTitle();
});