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

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

问题描述

我有一些容器,他们的孩子只是绝对的/相对定位。

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。

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

http: //jsfiddle.net/Ht9Qy/

任何容易解决的问题?

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

推荐答案

p>如果我明白你正在努力做什么,那么我不认为这是可能的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 和边距以获得相同的定位效果,同时保持文档流中的子项,然后可以使用

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天全站免登陆