HTML header balancing with CSS / jQuery

I have many h2 headers on one of my sites. Although most of these headings are โ€œbalancedโ€ (this is a word that I have formulated because I have no better way to explain this), some of them are unbalanced and look awful.

This is an example that should make it clear:

enter image description here

(The arrow shows the orphan word).

As you can see in the image above, the first heading has an orphan word with a long first line, and the second heading is more proportional.

Is there any way to achieve this effect without adding <br> tags to my headers?

I know that I could just resize the header container using the width attribute, but the problem will not go away as I try to avoid these orphan words.

I'm not even sure if there is a solution for this, but this is something that I was interested in for a while.

+5
source share
2 answers

A possible approach would be to reduce the width of the header until its number of rows increases. The width before increasing the number of lines is the final width of the header. This should make it look โ€œbalanced.โ€

Check out the working script that contains the code below.

 // "Balance" a jQuery element function balance($elem) { var originalWidth = $elem.width(), originalHeight = $elem.height(), currentWidth = originalWidth, currentHeight = originalHeight; // Decrement width until number of lines increases or // width becomes 0 while (currentHeight == originalHeight && currentWidth > 0) { $elem.width(currentWidth - 1); currentWidth = $elem.width(); currentHeight = $elem.height(); } if (currentWidth == 0) { // Reset width $elem.width(''); } else { // Restore width so that number of lines is maintained $elem.width(currentWidth + 1); } } 
+1
source

The code below works with the jQuery collection.

For each element in the collection, the width is changed to minimize the difference between the widest and thinnest client rectangles (using getClientRects ).

The code ensures that the number of client errors does not change. This prevents the element from expanding or enlarging.

getClientRects returns one rectangle for block level elements. For this reason, the code adds span to the element to preserve its HTML content, and the logic is based on the fact that span client rects. (Then the span is removed.)

 function balance(el) { el.each(function() { var temp= $('<br><span>'+$(this).html()+'</span>').appendTo(this), sp= $(this).find('span')[0], num= sp.getClientRects().length; for(var w=$(this).width(), i=10, best=10, delta=9999 ; i <= w ; i++) { $(this).width(i); var cr=sp.getClientRects(); if(cr.length > num) continue; for(var min=9999, max=0, j=0 ; j < cr.length; j++) { min= Math.min(min, cr[j].width); max= Math.max(max, cr[j].width); } if(max-min < delta) { delta= max-min; best= i; } } $(this).width(best); temp.remove(); }); }; 

Working script

0
source

Source: https://habr.com/ru/post/1216315/


All Articles