Expand a div to fill the remaining width

前端 未结 21 1474
一生所求
一生所求 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

    ...
    
    Some text
    Some other text
    ....

    javascript

    $(document).ready(function(){
        stretchDivs();
    });
    
    function stretchDivs() {
        // loop thru each 
    that has class='stretch' $("div.stretch").each(function(){ // get the inner width of this
    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")); } }); }); }

提交回复
热议问题