How to get rid of gap with position:relative banner

孤人 提交于 2020-01-17 01:39:07

问题


What's the recommended & most elegant way of getting rid of the gap caused by position:relative?

I have a front page and want to put a banner that will be partially above the header and content section, but using position:relative produces an empty area...

See example (I want the text to be just below the red box):

http://jsfiddle.net/Ru2CT/

I know I could create another relative positioned div as a parent of my text, but then I'll still have the gap but between content section & footer...

Any ideas? :)


回答1:


Take the entire contents of the grey box, and place it within a div (stretched to be the same size). Then move that box up with position:relative. This will have the effect of moving the text with the red "slider"/banner thing, without moving the gray background.

Here we go: http://jsfiddle.net/4BLFJ/ [animated and annotated]




回答2:


This is not what you asked, but is one of the two ways I would do it:

The main idea here is to make the banner an absolutely-positioned div (not absolutely-positioned on the page, though you can do that too; it may in fact be better).

First set the #content area to be position:relative, but NOT change anything else. This creates a new stacking context (child elements use top/right/bottom/left and percentages relative to it).

Then put the banner-thing as a child element of the #content area, and set it as follows:

position:absolute;
width:80%; height:100px; /*there are other ways to set the height and width*/
bottom:100%; /*this puts it at the top*/
/*you can also use bottom:105% or bottom:90% or other things, or if you really
  want to use non-relative units like px, you can create a third nested div that is
  relatively positioned by whatever px amount*/



回答3:


Negative margin would be a much more elegant solution in this situation (revised jsFiddle). Note that I've had to move the #eee background to div#main, as it would otherwise overlay on the background of div#top.

As a general rule of thumb, I'd also recommend avoiding relative positioning unless absolutely necessary - can often lead to z-index headaches in older versions of IE.




回答4:


I've finally resolved this issue, simple:

   position: relative;
   bottom: 200px;
   margin-bottom: -200px;

Does the magic! :)



来源:https://stackoverflow.com/questions/5689494/how-to-get-rid-of-gap-with-positionrelative-banner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!