The inline-block
indeed extends on resizing as your animation shows, so that it keeps place for the long word to go into that space again.
One simple solution would be to add text-align: justify
, but I'm afraid it may not exactly be what you want (see demo).
Another one would be the use of media queries
, as @Parody suggested, but you would have to know the dimentions of the containing div
, and that would not be very scalable as you mentionned.
The word-break: break-all
suggested by @yugi also works but causes the words to to collapse letter by letter, regardless of their length.
The only way to achieve the exact behavior is (as far as I know) to use javascript. For example, you would have to wrap your text into a span
element inside the div
, and then add something like this :
var paddingLeft = parseInt($('#foo').css('padding-left')),
paddingRight = parseInt($('#foo').css('padding-left')),
paddingTop = parseInt($('#foo').css('padding-top')),
paddingBottom = parseInt($('#foo').css('padding-Bottom')),
cloned = $('#foo span').clone(),
cloned_wrap = document.createElement('div');
$(cloned_wrap).css({
paddingLeft : paddingLeft,
paddingRight : paddingRight,
display : 'inline-block',
visibility: 'hidden',
float: 'left',
});
$(cloned_wrap).insertAfter('#foo');
cloned.appendTo(cloned_wrap);
$(window).on('resize', function(){
$('#foo').css('width', cloned.width() + 1);
$(cloned_wrap).css('margin-top',- $('#foo').height() - paddingTop - paddingBottom);
}).resize();
Please see the jsfiddle working demo. (← edited many times)
That's quite a lot of code, but it works ; )
(PS : I assumed jquery was available, if not, quite the same is achievable in pure JS)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…