html - 如何在不使用 float 的情况下向右浮动 inline-flex 的 div ?

标签 html css flexbox

我试图避免 float (或找到替代方案)将工具栏div移动到页面右侧,同时保持其size 其内容的大小。

所以,如果我简单地添加:

  float:right;

对于下面的.toolbar,我会得到看起来像我想要的东西,它基本上是一个占据其元素大小的容器(来自display:inline-flex) 与页面右侧对齐。

但是,我不想将其 float 到右侧(它可以工作,但我听说你应该避免它,我正在寻找 float 的替代方案)。

我确实尝试过使用 margin-left: auto; 但无法弄清楚(除非我取下了我需要的 flex:inline-flex父级大小。

有什么想法吗?

.page {
  padding: 20px;
}

.toolbar {
  background: lightgray;
  border: 1px solid black;
  padding: 5px;
  display: inline-flex;
  flex-direction: row;
  justify-content: flex-end;
}

.item {
  background: azure;
  border: 1px solid black;
  padding: 3px;
  margin: 3px;
}

.switchbox {
  display: inline-block;
}
<div class="page">
  <div class="toolbar">
    <div class="item switchbox">Switchbox Component</div>
    <button class="item button">Submit</button>
  </div>
</div>


最佳答案

您可以使用 flex 属性沿水平或垂直轴对齐元素。

要启用 Flex 属性,只需将父级设为 Flex 容器即可。

将其添加到您的代码中:

.page {
  display: flex;
  justify-content: flex-end;
}

.page {
  display: flex;
  justify-content: flex-end;
  padding: 20px;
}

.toolbar {
  background: lightgray;
  border: 1px solid black;
  padding: 5px;
  display: inline-flex;
  flex-direction: row;
  justify-content: flex-end;
}

.item {
  background: azure;
  border: 1px solid black;
  padding: 3px;
  margin: 3px;
}

.switchbox {
  display: inline-block;
}
<div class="page">
  <div class="toolbar">
    <div class="item switchbox">Switchbox Component</div>
    <button class="item button">Submit</button>
  </div>
</div>

或者你可以这样做:

.page {
  display: flex;
}

.toolbar {
  margin-left: auto;
}

.page {
  display: flex;
  padding: 20px;
}

.toolbar {
  margin-left: auto;
  background: lightgray;
  border: 1px solid black;
  padding: 5px;
  display: inline-flex;
  flex-direction: row;
  justify-content: flex-end;
}

.item {
  background: azure;
  border: 1px solid black;
  padding: 3px;
  margin: 3px;
}

.switchbox {
  display: inline-block;
}
<div class="page">
  <div class="toolbar">
    <div class="item switchbox">Switchbox Component</div>
    <button class="item button">Submit</button>
  </div>
</div>

更多详细信息:Understanding justify-content and auto margins

关于html - 如何在不使用 float 的情况下向右浮动 inline-flex 的 div ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55031000/

相关文章:

html - Flex 导航栏中的下拉子菜单未出现在按钮下方

html - 居中一个 flex 元素并底部对齐另一个

html - 带回丢失的输入类型日期清除字段按钮(Chromium)

html - 用于匹配所有 <img> 标记并提取 "src"属性的正则表达式

html - 将图像设置为 anchor 标记不起作用

html - {{variable}} 在页面加载时显示,然后替换为值

html - 使响应式 Bootstrap 表水平

即使最高值相同,JavasCript 函数也无法启动

html - 对 <head> 中的元素进行排序的最佳做法是什么?

javascript - 当容器有右滚动条时,Flex 元素宽度不能在 IE11 中工作