Absolute positioned, width by floated children, won't exceed its own parent

让人想犯罪 __ 提交于 2019-12-12 03:45:16

问题


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:


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/



来源:https://stackoverflow.com/questions/15237846/absolute-positioned-width-by-floated-children-wont-exceed-its-own-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!