Negative margin breaks float

会有一股神秘感。 提交于 2019-12-10 18:55:18

问题


While I was working on something, I noticed a very strange behaviour which I couldn't explain. The only difference between the two scenarios is that the <i>s in the second example have margin-top set to -10px instead of -9px. I use the negative margin to shift all of the boxes top with the same ammount.

main, aside {
  width: 100%;
  padding: 20px 0 10px;
  margin-bottom: 10px;
  overflow: hidden;
  background: lightblue;
}

main i, aside i {
  float: left;
  display: block;
  width: 10px;
  height: 10px;
  margin: -9px 0 0 5px;
  background: orange;
}

aside i {
  margin-top: -10px;
}
<main>
  <i></i>
  <i></i>
  <i></i>
</main>
<aside>
  <i></i>
  <i></i>
  <i></i>
</aside>

With only that tiny little change of the top margin they stack on top of each other instead of next to each other. I can't understand what is causing it. I confirmed this behaviour with Gecko and WebKit based browsers.


回答1:


I'll try an explanation (or better called, an interpretation) for the abnormal scenario. I can't be sure that what I interpret is correct because the specs have a lot of rules and also the browser implementation may not be completely according to the specs.

The first float box is positioned left most in the parent and shifted 10px upwards (because of the -10px margin). When the rendering searches for a position for the second box, it starts looking at height 0 of the parent and goes from right to left until it encounters another float, but it doesn't because the first float was shifted completely out of the parent, so it goes all the way to the left. If it happens like this, the 9 float positioning rules are still respected (more or less, again it depends on how the developers interpreted some things).

Also consider this disclaimer from the margins section:

Negative values for margin properties are allowed, but there may be implementation-specific limits.

You should understand from it that negative margins should be used at your own risk.

My recommendation is to give up on the negative top margin because it's, let's say, problematic, and use instead some shifting with position: relative (or don't shift at all).

Ref.:
https://www.w3.org/TR/CSS2/visuren.html#float-position https://www.w3.org/TR/CSS2/box.html#margin-properties



来源:https://stackoverflow.com/questions/35344103/negative-margin-breaks-float

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