Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

css - the behaviour of top: auto; bamboozles me

Hi I'm really confused about some basics with absolute positioning.

<!DOCTYPE html>
<html>
<head>    
<link href="http://yui.yahooapis.com/3.0.0/build/cssreset/reset-min.css" rel="stylesheet" type="text/css" />

<style>    
#containingBlock {
  position: relative;
  background: green;

}
#abs {
  position: absolute;
  background: blue;
  top: auto;
}  
</style>
</head>
<body>

<div id="containingBlock">

  <p>foo</p>

  <div id="abs">bar</div>

</div>

</body>
</html>

With the markup arranged as above, div#abs does not overlap the foo paragraph.

I know I could make it do this by giving top a value of 0 rather than auto, but since div#containingBlock has no padding, I thought auto and 0 would do the same thing.

However, if the paragraph and div#abs are switched in the source order -to make bar come before foo -top: auto; works exactly as I expected.

Any explanations appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You didn't really position these elements, you just declared what type of positioning you want to use. In this case, the auto value isn't really doing anything, because the #abs element is being placed right where it normally would anyways. If you removed the top: auto; segment outright, it would have no effect on the element.

"bar" is not overlapping "foo" because you haven't positioned it to do so. It is contained within the #containingBlock element, and is placed below the block element <p> because "foo" takes up a discrete amount of space. You want to override that? Set the top or other corresponding position values. To reiterate what others have said, top:auto just positions the top of that element as high up as room permits (which is what the element would have done normally).

For future reference, the auto value is used for when a parent CSS property overrides the child element's styling. For example let's say you had more complicated code which had a rule to apply a margin to every div within #containingBlock. If you want to change that back to normal, you would include margin:auto; in your containingBlock CSS.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...