负边距与相对定位
我遇到过许多涉及负边距的布局技术,例如用于侧边栏定位的经典 。看起来这些技术可以很容易地应用于相对定位。
因此,
.sidebar {
margin-left:-600px;
}
我们可以这样做:
.sidebar {
position:relative;
left:-600px;
}
看起来相对定位在垂直方向上甚至可能更清晰, 因为最高利润操纵可能会受到保证金崩溃等问题的影响。其中
一种相对于另一种是否有任何优势,或者它们实际上是否相同?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
相对定位会将内容向左移动,但原始空间将被它占据,除非您也将下一个元素设为相对位置。然而,当边距为负时,内容及其原始空间都会发生变化。
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.
简而言之,相对定位会在视觉上移动相对元素的内容,而不影响其在页面流中的位置。另一方面,边距会相对于元素的自然位置推动或拉动元素,从而影响布局。
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.
头寸属性和负保证金都有其用途,并且没有谁比另一个更好。这取决于您想要做什么。当您想要将每个元素从左、右、上、下移动时,您不必相对或绝对地定位每个元素。假设您有一个简单的
标记,您想要将其移动到左侧,您不会为其提供一个位置属性,只是为了移动它。保证金是正确的使用方法。边距将影响网站上其他元素的位置,其中位置将浮动而不影响其他元素的位置。位置属性虽然可以通过多种方式使用,但它主要用于使您的网站成为主要元素:例如,页眉,页脚,包装器,菜单,左侧内容,右侧内容。
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.