Absolute positioned, width by floated children, wo

2019-08-30 00:12发布

Okay, so this is a bit difficult to explain. Basically, I have a div positioned relative, holding a an absolutely positioned div. The absolutely positioned div contains divs with a fixed width, which are floated. These floated divs should expand the width of the absolute parent.

<div id="parent">
  <div id="stretchable-div">
    <div class="child">text</div>
    <div class="child">another text</div>
    <div class="child">more text</div>
  </div>
</div>

Problem being, this does not work when the original relative position div width is less than the absolute div.

Example - http://jsfiddle.net/8JJSf/91/

Can be done in jQuery by:

$('.dropdown').each(function(index){
var sum = 0;
$(this).find('.half').each( function(){ sum += $(this).outerWidth(); });
$(this).width( sum );
});

1条回答
虎瘦雄心在
2楼-- · 2019-08-30 01:13

You need to use JavaScript for this if you want to keep the position as absolute

When setting the position to absolute the element is no longer part of the regular page flow, and so the parent will have no knowledge of its children's sizes/positions.

edit: here's some jQuery code that sizes the parent based on the children. It will stretch the parent to match the widest child, and the height of all children. I'm no jQuery expert, so there might be a better/easier way. The parent height should be set to 0px initially.

$('#stretchable-div').each(function() {
    var parentWidth = $('#parent').width(),
        parentHeight = $('#parent').height(),
        childW = $(this).width() + $(this).position().left;

    if (childW > parentWidth) {
      $('#parent').width(childW);   
    }

    $('#parent').height($('#parent').height() + $(this).height() + $(this).position().top);   

});

http://jsfiddle.net/WHV7M/

查看更多
登录 后发表回答