容器内的相对/绝对定位

时间:2012-10-21 09:31:54

标签: javascript html css

我试图将一些div放在另一个容器中, 当我在这些div上设置position: relative;时,它们被绘制在容器内,但是当我添加topleft样式属性时,它们没有正确绘制

这是我的代码:

<table style="background:black;width:80%;height:90%;">
    <tr>
        <td style="background:yellow;width:15%">Left Pane</td>
        <td style="background:black;width:85%">
            <div id="a" style="background:green;position:relative;top:1px;left:80px;width:20%;height:20%">a</div>
            <div id="b" style="background:blue;position:relative;top:10px;left:14px;width:20%;height:20%">b</div>
            <div id="c" style="background:red;position:relative;top:10px;left:14px;width:20%;height:20%">c</div>
        </td>
    </tr>
</table>

你可以看到div #b&amp; #ctop&amp; left属性,但它们彼此相互映射, 如果我设置position: absolute;它们彼此放置,但它们不是根据容器定位,而是根据屏幕定位。

有没有办法根据容器将div放在彼此的顶部?

3 个答案:

答案 0 :(得分:1)

了解相对和绝对的位置:

css tricks: position relative and absolute

简而言之:

容器元素获得position: relative;

其中的元素,获取position: absolute;top/bottom/left/right

的值

这允许您控制定位并且它是跨浏览器兼容的(旧版本的IE以可怕的方式处理定位!)

PS一些提高编码技能的通用建议:

  • 尽量避免使用表格进行布局。

  • 使用外部css文件而不是内联 - 从长远来看,它更容易保留并且可以重复使用。

答案 1 :(得分:0)

对容器使用position: relative,对内部元素使用position: absolute

<td style="position: relative">
  <div id="a" style="position: absolute; top:1px;left:80px;width:20%;height:20%">a</div>
  <div id="b" style="position: absolute; top:10px;left:14px;width:20%;height:20%">b</div>
  <div id="c" style="position: absolute; top:10px;left:14px;width:20%;height:20%">c</div>
</td>

答案 2 :(得分:0)

您需要使用相对定位的父级并绝对定位div:请参阅我的js小提琴:

http://jsfiddle.net/benedict_w/VeL3c/

<body>
<table>
    <tr>
        <td class="left">Left Pane</td>
        <td class="right">
            <div id="a">a</div>
            <div id="b">b</div>
            <div id="c">c</div>
        </td>
    </tr>
</table>
</body>​

CSS

table {
    background:black; width:80%; height:90%;
}

td.left {
    background:yellow; width:15%;
}

td.right {
    position: relative; background:black; width:85%
}

#a, #b, #c {
    position:absolute; top:0px;
}

#a {
    background:green;left:80px; width:20%;
}

#b, #c {
    left:14px;width:20%;
    background: blue;
}

#c {
    background:red;
}
相关问题