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
306 views
in Technique[技术] by (71.8m points)

css - Difference between static and relative positioning

In CSS, what is the difference between static (default) positioning and relative positioning?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Static positioning is the default positioning model for elements. They are displayed in the page where they rendered as part of normal HTML flow. Statically positioned elements don't obey left, top, right and bottom rules:

statically-positioned elements obey normal HTML flow.

Relative positioning allows you to specify a specific offset (left, top etc) which is relative to the element's normal position in HTML flow. So if I have a textbox inside a div I could apply relative positioning on the textbox to have it display at specific place relative to where it would normally be placed within the div:

relatively-positioned elements obey HTML flow, but provide the ability to adjust their position relative to their normal position in HTML flow.

There is also absolute positioning - whereby you specify the exact location of the element relative to the entire document, or the next relatively positioned element further up the element tree:

absolutely-positioned elements are taken out of HTML flow and can be positioned at a specific place in the document...

And when a position: relative is applied to a parent element in the hierarchy:

...or positioned relative to the first parent element in the HTML tree that is relatively positioned.

Note how our absolutely-position element is bound by the relatively-positioned element.

And lastly there is fixed. Fixed positioning restricts an element to a specific position in the viewport, which stays in place during scroll:

fixed-positioned elements are also taken out of HTML flow, but are not bound by the viewport and will not scroll with the page.

You may also observe the behaviour that fixed-positioned elements do not cause scroll because they are not considered to be bound by the viewport:

fixed-positioned elements have no effect on scroll.

Whereas absolutely-positioned elements are still bound by the viewport and will cause scrolling:

absolutely-positioned elements are still affected by the boundaries of the viewport, unless overflow is used on a parent element.

..unless of course your parent element uses overflow: ? to determine the behaviour of the scroll (if any).

With absolute positioning and fixed positioning, the elements are taken out of HTML flow.


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

...