[英]How to position <div> absolute to parent and relative to neighbors
I'm working on a simple little project right now and I can't seem to figure out the styling. 我现在正在做一个简单的小项目,似乎无法弄清楚样式。
Basically, what I need to do is position a 'div' a certain number of pixels down from the top of its parent. 基本上,我需要做的是将“ div”从其父级的顶部向下定位一定数量的像素。 To do this I made its position absolute and set top to whatever pixel offset I need.
为此,我将其位置设为绝对,并将顶部设置为所需的任何像素偏移。 The problem with this is sometimes two 'div's will be at the same vertical position (or close to it) in the parent and will overlap.
这样做的问题是,有时两个“ div”在父级中会处于相同的垂直位置(或接近它),并且会重叠。 I need to have them line up side by side horizontally when they are overlapping.
当它们重叠时,我需要使它们水平并排排列。 I know how to do this with a position of relative and the float property but this then breaks the vertical positioning.
我知道如何使用相对位置和float属性来执行此操作,但这会破坏垂直位置。
The boxes are inserted dynamically with jQuery and their positions can change frequently. 这些框是使用jQuery动态插入的,它们的位置可以经常更改。
Here is a jsfiddle to demonstrate. 这是一个演示的jsfiddle 。
HTML HTML
<div class="main">
This is okay
<div style="top: 25px;" class="sub">
<h3>
test
</h3>
</div>
<div style="top: 100px;" class="sub">
<h3>
test
</h3>
</div>
<div style="position: absolute; top: 200px;">
This is the problem
</div>
<div style="top: 250px;" class="sub">
<h3>
test
</h3>
</div>
<div style="top: 260px;" class="sub">
<h3>
test
</h3>
</div>
</div>
CSS CSS
.main {
background-color: grey;
height: 700px;
}
.sub {
border: thin solid black;
position: absolute;
}
you may make the sub div's inside other div and give this one absolute position 您可以将子div放在其他div内,并给出这一绝对位置
.main { position:relative; background-color: grey; width:100%; height:auto; } .sub { position: absolute; top:100px; width:100%; } .child { border:2px solid black; width:500px; height:500px; margin:10px auto; }
<div class="main"> <div class="sub"> <div class="child"></div> <div class="child"></div> </div> </div>
if you want them horizontally add to .child 如果要水平将它们添加到.child
float:left;
width:47%;
margin:1%;
As far as I can tell this isn't solvable with CSS. 据我所知,这是无法用CSS解决的。 I ended up doing some decently complex javascript to detect collisions and reposition the div's appropriately.
我最后做了一些相当复杂的JavaScript,以检测冲突并适当地重新定位div的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.