为什么不使用边距定位,而不是使用position:relative top 5px? [英] Why not use margin positioning instead of using position:relative top 5px?

查看:233
本文介绍了为什么不使用边距定位,而不是使用position:relative top 5px?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题,基本上。我一直在做许多我的工作,使用利润率定位,而不是像位置:相对的东西,只是因为我不知道你可以控制它的方式。

Title, basically. I've been doing a lot of my work using margin positoning instead of stuff like position:relative, just because I wasn't aware you could control it that way. What is margin supposed to do, and why am I supposed to use position when margin gets the job done?

谢谢!

推荐答案

简而言之,边距会在元素框周围添加空间,并修改页面流中要保留的空间大小以匹配。因此,上边距会将一个块向下移动,同时也会移动其后面的所有内容。底部边距移动其后的内容,同时将块本身保留在相同的位置。

In a nutshell, margins add space around an element's box and modifies the amount of space reserved for it in the page flow to match. So a top margin moves a block down, while also moving all content that follows it down. A bottom margin moves content that follows it down while leaving the block itself in the same place. That's very intuitive and probably behaves exactly how you'd expect.

相对定位有些奇怪:它改变了绘制的区块,但是不是为它保留的空间。所以,如果你使用相对定位和设置顶部到10px,一个框将被移动10px向下的页面 - 但内容后,它不会移动。这可能会导致一个框与其后的内容重叠。

Relative positioning does something strange: it changes where a block is drawn, but not where the space reserved for it is. So, if you use relative positioning and set top to 10px, a box will be moved 10px down the page -- but content after it will not move. That could cause a box to overlap with the content following it.

如果你真的想要一个奇怪的效果(并看到相对定位在行动),应用两个float:left和相对定位到一个小块。块将被移动,但为其保留的区域将保持在其原始位置。

If you really want a strange effect (and to see relative positioning in action), apply both float: left and relative positioning to a small block. The block will be moved, but the area reserved for it will stay in its original place.

我为你做了一个例子:

<div style="position: relative; left: -100px; width: 100px; height: 100px; float: left;">
</div> (lorem ipsum text)

小提琴

Fiddle

这篇关于为什么不使用边距定位,而不是使用position:relative top 5px?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆