Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make top line shorter than bottom line (within div)

I have an unordered list which contains 3 list items (represented in my example as 3 green boxes). Each box has an image and 3 divs (title,location,price). I'm only concerned with each box's title div.

If the title is long enough so that it produces 2 lines, I want the top line to always be shorter than the bottom line. My demo site seen here shows boxes 1 & 2 with the wrong setup, and box #3 shows the correct setup.

I'm having trouble... this may require js to determine line length and then set the bottom line to be longer. Screen resolution will likely play a role but can't I make the lines consistent across different screen sizes?

Here is one of the list items, I'm interested in the div "titlebox":

<li class="list__item">
            <figure class="list__item__inner">

   <p class="vignette" style="background-image:url(http://www.ht-real-estate.com/template/ht2014/images/landscape/05.jpg)"></p>
   <div class="titlebox">This line is longer than this line</div>
   <div class="locationbox">Location</div>
   <div class="pricebox">Price</div>

</li>

Any help is great, thanks!!

Screenshot attached too: Screenshot

like image 611
Nova Avatar asked Nov 09 '22 19:11

Nova


1 Answers

Here is a JS solution that might work for you in most instances (I say most instances because text characters can have varying widths). It basically splits your sentences into 2 lines with a dynamically inserted <br> tag. Comments in the code:

$(".titlebox").each(function(){
  var len = $(this).text().length,
      words = $(this).text().split(" "),
      line1 = [],
      line2 = [],
      html = "";

  // iterate through each word in the title
  $.each(words, function(i,word){
    // if line 1's current length plus the length of this word
    // is less than half the total characters, add word to line 1
    // else add to line 2
    // (check index of word to maintain order)
    if((line1.join(" ")+" "+word).length < (len/2) && (i == line1.length)){
      line1.push(word);
    } else {
      line2.push(word);
    }
  });

  // concatenate the results with a '<br>' separating the lines
  html = line1.join(" ")+"<br>"+line2.join(" ");

  // replace the .titlebox content with this new html string
  $(this).html(html);
});
like image 128
SteamDev Avatar answered Nov 14 '22 23:11

SteamDev