Place particular word at center
http://stackoverflow.com/questions/21506427
HTML
<center>Once upon a time, there was a squirrel who lived in the <span class="centered">middle</span> of the forest. I say middle, but without knowing where the edges were, the squirrel had no idea where the center was.</center>
CSS
center {
width: 280px;
position: absolute;
top: 200px;
left: 50px;
}
.centered {
background: rgba(0,128,0,0.2);
}
.clear {
background: rgba(255,0,0,0.2);
}
.clear:after {
content: '';
display: block;
clear: both;
}
JavaScript
jQuery.fn.findYourCenter = function( target ){
base = $(this);
target = base.children(target);
base.contents().eq(0).each(function(){
var i = -1, word, words, found, dif,
last = Infinity,
node = $(this),
text = node.text().split(/\s+/),
cwidth = Math.round(target.width() * 0.5),
bwidth = Math.round(base.width() * 0.5),
breaks = 2
;
node.replaceWith(
'<span class="word">'+text.join(' </span><span class="word">')+' </span>'
);
words = base.find('.word');
do {
while ( ++i < words.length ){
word && word.removeClass('clear');
word = words.eq(i).addClass('clear');
dif = Math.round(Math.abs((target.position().left + cwidth) - bwidth));
if ( dif < last ) {
last = dif;
found = i;
}
}
word.removeClass('clear');
if ( found ) {
words.eq(found).addClass('clear');
i = found; found = word = null;
}
else {
break;
}
} while ( i < words.length && --breaks );
});
};
jQuery(function($){
$('center').findYourCenter('.centered');
});