我试图在另一个容器中定位一些div,当我在这些div上设置position: relative;
时,它们会在容器内绘制,但是当我添加top
和left
样式属性时,它们不能正确绘制
下面是我的代码:
<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>
正如你所看到的,#b
和#c
应该放在一起,因为它们的top
和left
属性,但它们是在彼此下面绘制的,如果我设置position: absolute;
,它们会放在另一个上面,但它们不是根据容器而是根据屏幕定位的。
有没有办法根据它们的容器将div放在彼此的顶部?
发布于 2012-10-21 09:34:29
了解相对位置和绝对位置:
css tricks: position relative and absolute
简而言之:
容器元素获取position: relative;
其中的元素获取top/bottom/left/right
的position: absolute;
和值
这让你可以控制定位,而且它是跨浏览器兼容的(旧版本的IE处理定位的方式很糟糕!)
PS一些通用的建议,以提高您的编码技能:
发布于 2012-10-21 09:34:39
容器使用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>
发布于 2012-10-21 09:50:56
您需要使用相对定位的父对象,并绝对定位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;
}
https://stackoverflow.com/questions/12996643
复制