开发者

Is it possible to have auto margins when you have position:absolute?

I'm having an issue where a div is not butting up to the very top of the page. I tried to solve this by adding

position:absolute;
top:0px;

which put it at the top like I wanted but it also went to the left of the page. I want it to be centered in the page which works if I use auto left and right margins without position:absolute.

Is there an开发者_开发百科y way to have auto margins AND position it at the very top of the page?


I think you have to set left and right (or maybe only left) to 50%

left:50%;
right:50%;


Not an answer to your question, but this sounds like a hacky solution. Don't use position: absolute to solve spacing issues - it has too many other consequences, some of which we can't even see that become apparent on smaller resolutions and such.

Better use Firebug or a similar tool to find out what is causing the space, and fix the reason. It's annoying, but really worth the time.

If you really need to do this, one solution might be to put the position: absolute on a div that spans across the whole screen (width: 100%) and put the real div in there - presumably with the correct margins. (I can't build a test case right now so I can't guarantee 100% that this will work.)


position: absolute takes elements out of the normal flow calculations, so I'm not sure whether or not you can have auto-margins.

Either way, it's generally a bad idea for something like that. My advice is to look into why it's not butting up against the top of the page with normal positioning instead.

I never get that problem because the first thing I do in all of my stylesheets is reset all margins and padding to zero and then redefine them explicitly.

In your case, this might be enough:

html, body {
  margin-top: 0;
  padding-top: 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜