首页 > 解决方案 > 当我给 margin 0 0 0 auto 时,它应该转到最右边,但输出中没有应用样式

问题描述

在这种情况下,在边距中,最后一个是左,因此在这种情况下它被指定为自动。所以它应该在它的最右边。但它没有发生。我想知道这背后的逻辑。

.follow-btn {
    margin: 0 0 0 auto ;
 }
<div class="follow-btn">
    <button>Follow</button>
 </div>

标签: htmlcssmarginmargin-left

解决方案


您将边距应用于 div,默认情况下填充页面的整个宽度。因此,为了确保auto左侧的边距将其推到右侧,您可以指定一个指定的宽度,使其实际上浮动到右侧。

所以这改变了你的例子:

.follow-btn {
  margin: 0 0 0 auto;
  background: red; /* just to show the effect on the div */
}
<div class="follow-btn">
    <button>Follow</button>
</div>

对此:

.follow-btn {
  margin: 0 0 0 auto;
  background: red; /* just to show the effect on the div */
  width: 4em;
}
<div class="follow-btn">
    <button>Follow</button>
</div>


推荐阅读