绝对位置,浮动儿童的宽度,不会超过其父级的宽度 [英] Absolute positioned, width by floated children, won't exceed its own parent

查看:103
本文介绍了绝对位置,浮动儿童的宽度,不会超过其父级的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,这有点难以解释。基本上,我有一个相对位置的div,并持有一个绝对位置的div。绝对定位的div包含固定宽度的div,这些div是浮动的。这些浮动的div应该扩大绝对父级的宽度。

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>

问题是,当原始相对位置div宽度小于绝对div时,此方法不起作用。

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

示例- http://jsfiddle.net/8JJSf / 91 /

可以在jQuery中通过以下方式完成:

Can be done in jQuery by:

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


推荐答案

如果您要使用JavaScript,将位置保持为绝对

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.

编辑:这是一些jQuery代码,可根据子代调整父代的大小。它将使父项拉伸以匹配最大的子项以及所有子项的身高。我不是jQuery专家,所以可能会有更好/更简便的方法。父高度最初应设置为0px。

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/

这篇关于绝对位置,浮动儿童的宽度,不会超过其父级的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆