Inline-block line-wrap extra space

前端 未结 4 1921
无人及你
无人及你 2020-12-14 19:15

I\'ve got an inline-block element that contains a very long word. When I resize the viewport until I reach the breakpoint of the text wrapping to the next line, I get a subs

4条回答
  •  被撕碎了的回忆
    2020-12-14 20:15

    I am still very appreciative of @lapin's answer (which I accepted and awarded bounty to), I found out after the fact that it didn't quite work on multiple elements next to each other (that has nothing to do with @lapin, I just didn't mention it in my original question as I thought it would be irrelevant information).

    Anyway, I've come up with the following that works for me (assuming the elements it should be applied to are .title and .subtitle):

    $('.title, .subtitle').each(function(i, el) {
        var el = $(el),
            inner = $(document.createElement('span')),
            bar = $(document.createElement('span'));
    
        inner.addClass('inner');
        bar.addClass('bar');
    
        el.wrapInner(inner)
            .append(bar)
            .css({
                backgroundColor: 'transparent'
            });
    });
    
    function shrinkWrap() {
        $('.title, .subtitle').each(function(i, el) {
            var el = $(el),
                inner = $('.inner', el),
                bar = $('.bar', el),
                innerWidth = inner.width();
    
            bar.css({
                bottom: 0,
                width: innerWidth + parseFloat(el.css('paddingLeft')) + parseFloat(el.css('paddingRight'))
            });
        });
    }
    shrinkWrap();
    
    $(window).on('resize', function() {
        shrinkWrap();
    });
    

    Basically what I do is:

    1. put the text in an inner wrap element
    2. create an additional absolutely-positioned background element
    3. get the width of the inline inner wrap element
    4. apply said width to the background element (plus padding and whatnot)

    The CSS:

    .title, .subtitle {
        position: relative;
        z-index: 500;
        display: table;
        padding-left: 10px;
        margin-right: 10px;
        background-color: red;
    }
    
    .title .bar, .subtitle .bar {
        position: absolute;
        top: 0;
        left: 0;
        bottom: 0;
        z-index: -10;
        background-color: red;
    }
    

提交回复
热议问题