Expand a div to fill the remaining width

前端 未结 21 1236
一生所求
一生所求 2020-11-21 22:21

I want a two-column div layout, where each one can have variable width e.g.

相关标签:
21条回答
  • 2020-11-21 23:14

    I wrote a javascript function that I call from jQuery $(document).ready(). This will parse all children of the parent div and only update the right most child.

    html

    ...
    <div class="stretch">
    <div style="padding-left: 5px; padding-right: 5px; display: inline-block;">Some text
    </div>
    <div class="underline" style="display: inline-block;">Some other text
    </div>
    </div>
    ....
    

    javascript

    $(document).ready(function(){
        stretchDivs();
    });
    
    function stretchDivs() {
        // loop thru each <div> that has class='stretch'
        $("div.stretch").each(function(){
            // get the inner width of this <div> that has class='stretch'
            var totalW = parseInt($(this).css("width"));
            // loop thru each child node
            $(this).children().each(function(){
                // subtract the margins, borders and padding
                totalW -= (parseInt($(this).css("margin-left")) 
                         + parseInt($(this).css("border-left-width")) 
                         + parseInt($(this).css("padding-left"))
                         + parseInt($(this).css("margin-right")) 
                         + parseInt($(this).css("border-right-width")) 
                         + parseInt($(this).css("padding-right")));
                // if this is the last child, we can set its width
                if ($(this).is(":last-child")) {
                    $(this).css("width","" + (totalW - 1 /* fudge factor */) + "px");
                } else {
                    // this is not the last child, so subtract its width too
                    totalW -= parseInt($(this).css("width"));
                }
            });
        });
    }
    
    0 讨论(0)
  • 2020-11-21 23:15

    If the width of the other column is fixed, how about using the calc CSS function working for all common browsers:

    width: calc(100% - 20px) /* 20px being the first column's width */
    

    This way the width of the second row will be calculated (i.e. remaining width) and applied responsively.

    0 讨论(0)
  • 2020-11-21 23:18

    I don't understand why people are willing to work so hard to find a pure-CSS solution for simple columnar layouts that are SO EASY using the old TABLE tag.

    All Browsers still have the table layout logic... Call me a dinosaur perhaps, but I say let it help you.

    <table WIDTH=100% border=0 cellspacing=0 cellpadding=2>
      <tr>
        <td WIDTH="1" NOWRAP bgcolor="#E0E0E0">Tree</td>
        <td bgcolor="#F0F0F0">View</td>
      </tr>
    </table>

    Much less risky in terms of cross-browser compatibility too.

    0 讨论(0)
提交回复
热议问题