[英]Relative/Absolute positioning inside container
当我设置position: relative;
时,我试图将一些div放置在另一个容器中position: relative;
在这些div上,它们绘制在容器内,但是当我添加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>
如您所见,div #b
和#c
应当由于其top
和left
属性而彼此放置,但它们是在彼此下方绘制的position: absolute;
它们彼此放置,但是它们的位置不是根据其容器而是根据屏幕。
有什么方法可以将div根据其容器彼此放置?
了解相对位置和绝对位置:
简而言之:
容器元素的position: relative;
里面的元素,获取position: absolute;
和top/bottom/left/right
这使您可以控制定位,并且它与跨浏览器兼容(旧版本的IE手柄定位非常糟糕!)
附上一些一般建议,以提高您的编码技能:
尽量避免使用表格进行布局。
使用外部CSS文件而不是内联文件-从长远来看更易于维护和重复使用。
使用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>
您需要使用相对定位的父级,并绝对定位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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.