Negative margins vs relative positioning

喜欢而已 提交于 2019-11-27 04:25:15

问题


I've come across many layout techniques involving negative margins, such as this classic for sidebar positioning. It seems like these techniques could just as easily be applied with relative positioning.

So instead of this:

.sidebar {
    margin-left:-600px;
}

One would do this:

.sidebar {
    position:relative;
    left:-600px;
}

It seems like relative positioning might even be cleaner in the vertical direction, as top-margin manipulation may be affected by collapsing margin issues, etc.

Is there any advantage to one over the other, or are they practically equivalent?

Thanks-


回答1:


I guess relative positioning will shift the content to left but the original space will be occupied by it unless you make the next element relative too. However with negative margin the content and its original space both are shifted.




回答2:


Put (more) simply, relative positioning will visually shift the contents of the relative element, without affecting its place in the page flow. Margins, on the other hand, push or pull elements relative to their natural position, and so affect layout.




回答3:


Both the position property and negative margin have there uses and no one is better then the other. It depends on what you are trying to do. You don't position every element relatively or absolutely when you want to shift it left right top bottom. Let's say you have a simple <p> tag that you want to move to the left, you don't give it a position property just to move it around. Margin is the proper method to use. Margin will affect the position of other elements on your site where as position will float without affect other elements positioning. The position property although can be used in many ways, it's mainly used for main elements that makes your site ex: example, header, footer, wrapper, menu, content left, content right.



来源:https://stackoverflow.com/questions/5256211/negative-margins-vs-relative-positioning

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