相对div与css一起徘徊

时间:2012-07-26 16:55:22

标签: css positioning z-index

问题并非如此简单(正如您可能想象的那样),请采用以下示例:

HTML:

Text text text <div id="special-image"></div> special content More text text text text... 


我希望输出看起来像:

enter image description here

正如您所见,#special-image正在“悬停”在内容上而不触及它 我知道首先想到的是position:absolute;
但正如您在示例图像中看到的那样,我希望这些div为position:relative到设置它们的区域(在html中)。并且x,y位置可以从页面到页面不同(它们不一致)。

页面中的文字应保持“锚定”在页面中,我不能给它绝对的位置。重点是我不希望#special-image div移动任何文本并将其悬停在那里。

你有什么建议我应该做的才能实现这种行为?

提前致谢。


修改
这又向前迈进了一步(感谢@Ross McLellan),
但新创建的div正在推动内容:
http://jsbin.com/isepow/1/
我需要一个图像而不是橙色背景。

3 个答案:

答案 0 :(得分:2)

如果您知道图像/图像保持器的宽度

,我认为可以通过一些负边距来实现

不在IE7中工作......

<div>Text text text <div id="special-image" style="display: inline-block; position: relative; top: -15px; left: -15px; width: 40px; margin-right: -40px; background-color: #ff6600;">&nbsp;</div> special content More text text text text... </div>

在Chrome中无效...

<div>Text text text <div id="special-image" style="position: absolute; margin-top: -15px; margin-left: -5px; width: 40px; background-color: #ff6600;">&nbsp;</div> special content More text text text text... </div>

如果允许额外的包装,则替代解决方案:

<div>Text text text <div style="position: absolute; display: inline;"><div id="special-image" style="display: inline-block; position: relative; top: -15px; left: -15px; width: 40px; background-color: #ff6600;">&nbsp;</div></div> special content More text text text text... </div>

外包装保持位置绝对样式。这允许特殊图像相对移动而不影响页面的其余部分

修改 可能修复了IE7使用边距的问题。不知道为什么,但事实上他们是在<div>,而是使用跨度而且它看起来很开心(在我的测试中没有移动任何其他文本)

Text text text<span id="special-image" style="position: relative; top: -15px; left: -15px; display: inline-block; width: 40px; margin-right: -40px; background-color: #ff6600;">&nbsp;</span> special content More text text text text...

答案 1 :(得分:0)

对我而言,目前尚不清楚是什么定义了两幅图像的位置。如果图像应接近特殊内容文本,则将此文本与图像放在一个单独的div中。然后,您可以相对于其父div定位图像。

答案 2 :(得分:0)

喜欢这个?

div#special-image{position:absolute;top:-5px; display:inline-block;}​

请参阅this作为概念证明; - )