【问题标题】:Why is margin: 0 0 0 auto not working without display: flex?为什么边距:0 0 0 自动在没有显示的情况下无法工作:flex?
【发布时间】:2022-01-15 00:10:32
【问题描述】:

使用下面的代码,我试图点击屏幕右侧的“关注”按钮。为此,我在 .follow 类中使用了 margin: 0 0 0 auto。当我在父元素(这里是标题元素)中使用 display: flex 时它可以工作,但是当我从父元素中删除 display: flex 时,它就会出现我的名字。为什么会这样?

header {
  display: flex;
  font-family: Montserrat, monospace;
  font-weight: 200;
}

.profile-pic {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  border: 2px;
}

.name {
  margin-left: 10px;
}

.username {
  margin-left: 10px;
}

.follow {
  margin: 0 0 0 auto;
  border: 0;
  border-radius: 10px;
}
<header>
  <img src="pic1.jpg" alt="Azraf Khan Zarif" class="profile-pic">
  <div class="name">Azraf Khan Zarif</div>
  <div class="username">@Zarif</div>
  <button class="follow">Follow</button>
</header>

【问题讨论】:

  • 试试float: right;
  • 因为margin: 0 0 0 auto; 用于右对齐流入块级元素,而您的按钮是内联级

标签: html css flexbox margin


【解决方案1】:

当您输入 display: flex; 时,它还会添加 flex-direction: row; 作为 flex 的默认行为。

因为您在&lt;header&gt; 中的所有孩子都被呈现为一行。

还将margin: 0 0 0 auto 添加到您的关注按钮中,将其移动到整个弹性行区域内的右上角。 如果你删除它,你会看到Follow 按钮出现在"@Zarif" 文本旁边

【讨论】:

    【解决方案2】:

    因为这就是 Flexible Box Module 的工作原理。将display: flex 指令放在header 元素中使其成为flexbox 容器,默认值为flex-direction: rowjustify-content: flex-start。这与margin: 0 0 0 auto 一起将按钮放在右侧。

    没有 flexbox,你可以达到同样的效果:

    header {
        position: relative;
        ...
    }
    
    .follow {
        position: abolute;
        top: 0;
        right: 0;
        ...
    }
    

    这样做,按钮将被放置在右上角,因为现在它会根据“父坐标”定位:代码会告诉按钮将0px从顶部移开,@987654328 @远离右边。

    【讨论】:

      猜你喜欢
      • 2020-11-28
      • 1970-01-01
      • 2017-09-23
      • 2015-10-16
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 2018-05-08
      • 1970-01-01
      相关资源
      最近更新 更多