位置:绝对和父高度? [英] Position: absolute and parent height?

查看:24
本文介绍了位置:绝对和父高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些容器,它们的孩子只是绝对/相对定位.如何设置容器高度以便他们的孩子在其中?

I have some containers and their children are only absolute / relatively positioned. How to set containers height so their children will be inside of them?

代码如下:

HTML

<section id="foo">
    <header>Foo</header>
    <article>
        <div class="one"></div>
        <div class="two"></div>
    </article>
</section>    

<div style="clear:both">Clear won't do.</div>
<!-- I want to have a gap between sections here -->

<section id="bar">
    <header>bar</header>
    <article>
        <div class="one"></div><div></div>
        <div class="two"></div>
    </article>
</section>  

CSS

article {
    position: relative;
}

.one {
    position: absolute;
    top: 10px;
    left: 10px;
    background: red;
    width: 30px;
    height: 30px;
}

.two {
    position: absolute;
    top: 10px;
    right: 10px;
    background: blue;
    width: 30px;
    height: 30px;
}

这是一个 jsfiddle.我希望条形"文本出现在 4 个方块之间,而不是在它们后面.

Here's a jsfiddle. I want "bar" text to appear between 4 squares, not behind them.

http://jsfiddle.net/Ht9Qy/

有什么简单的修复方法吗?

Any easy fixes?

注意,我不知道这些孩子的身高,我也不能为容器设置height:xxx.

推荐答案

如果我理解您要正确执行的操作,那么我认为在保持孩子绝对定位的同时使用 CSS 是不可能的.

If I understand what you're trying to do correctly, then I don't think this is possible with CSS while keeping the children absolutely positioned.

绝对定位的元素完全从文档流中删除,因此它们的尺寸不能改变其父级的尺寸.

Absolutely positioned elements are completely removed from the document flow, and thus their dimensions cannot alter the dimensions of their parents.

如果你真的必须在保持孩子为position: absolute的同时达到这种效果,你可以通过在JavaScript中找到绝对定位后的孩子的高度来做到这一点他们已经渲染,并使用它来设置父级的高度.

If you really had to achieve this affect while keeping the children as position: absolute, you could do so with JavaScript by finding the height of the absolutely positioned children after they have rendered, and using that to set the height of the parent.

或者,只需使用 float:left/float:right 和边距来获得相同的定位效果,同时将子项保持在文档流中,然后您可以使用 overflow: hidden 在父级(或任何其他清除技术)上,使其高度扩展到其子级的高度.

Alternatively, just use float: left/float:right and margins to get the same positioning effect while keeping the children in the document flow, you can then use overflow: hidden on the parent (or any other clearfix technique) to cause its height to expand to that of its children.

article {
    position: relative;
    overflow: hidden;
}

.one {
    position: relative;
    float: left;
    margin-top: 10px;
    margin-left: 10px;
    background: red;
    width: 30px;
    height: 30px;
}

.two {
    position: relative;
    float: right;
    margin-top: 10px;
    margin-right: 10px;
    background: blue;
    width: 30px;
    height: 30px;
}

这篇关于位置:绝对和父高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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