css - 如何使两个元素在 flexbox 中对齐到末尾

标签 css flexbox

我想实现一个如下图所示的组件。按钮的行为应始终与最右侧内部容器的末尾对齐,即使内部容器随着窗口尺寸变小而换行也是如此。内部容器应始终向左对齐,因此添加 align-self: flex-end;对于内部容器不是正确的方法。我对此一无所知。请帮忙!谢谢!

.container {
  display: flex;
  flex-direction: column;
}

.btn {
  display: flex;
  align-self: flex-end;
}

.inner-container {
  display: flex;
  flex-wrap: wrap;
}

.inner-container>div {
  margin-right: 10px;
}
<div class="container">
  <button type="button" class="btn">Click Me!</button>
  <div class="inner-container">
    <div>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(sample content in inner container)</div>
    <div>bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(sample content in inner container)</div>
    <div>cccccccccccccccccccccccccccccccccccccc(sample content in inner container)</div>
  </div>
</div>

https://codepen.io/anon/pen/WVXoNW

enter image description here

最佳答案

编辑

我的第一个解决方案真的很缺乏。这是一个更好的:

/*The main container is a grid. It will create 1 column and 2 rows automaticaly*/

.container {
  max-width: 1000px;
  display: grid;
}

/* I place the button in the 1st row, 1st column and justify it at 
   the end of the row */

.btn {
  justify-self:end;
  grid-row: 1;
  grid-column: 1;
}

/* I place the inner-container in the 2nd row and 1 first column, */
/* Make it a grid */
/* And generate columns with auto-fit and minmax(). This way columns will stretch
   to the maximum or wrap if they are under the minimum */
/* The important thing here is that the width of the main container grid will 
   be determined by this second grid, so the button will always be aligned 
   with the largest row of the inner-container */

.inner-container {
  width: 100%;
  grid-row: 2;
  grid-column: 1;
  display: grid;
  grid-template-columns : repeat(auto-fit, minmax(300px, 1fr));
}

Here is a pen对于此代码。

这里 flexbox 的问题是容器宽度在包装发生时不会调整大小。这就是我改用 2 个网格的原因。

注意:我正在使用 JS 开发一个 flexbox 版本来调整内部容器的宽度,但它比我刚刚提出的解决方案更复杂。

/p>

原创

正如本杰明所说,网格可能是可行的方法。

CSS:

.container {
  display: grid;
  grid-template-rows: 50px 200px;
  justify-items: center;
}

.btn {
  justify-self:end;
}

这就是我所做的全部更改,并且我保留了 inner-container 的显示 flex ,以保持您想要的环绕效果。在 grid 容器中有一个 flex 容器是没有问题的。

可以进行一些调整以使其更精确地满足您的需求。
如果您有任何疑问或精确度,请随时发表评论。

关于css - 如何使两个元素在 flexbox 中对齐到末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57351176/

相关文章:

css - 使绝对定位的 child 不会超出视口(viewport)边界

java - CSS 文件未加载到 Maven 元素中

css - 带有 Flexbox 的输入元素在 Webkit 中添加了额外的间距

css - 嵌套的 Grid/Flexbox 标题将内容向下推

html - 为什么 flex 元素不缩小超过内容大小?

html - Flex 框行换行在 Safari 中不起作用。尝试了多个前缀?

javascript - 使用 createElement Javascript 制作的定位图像

css - 为什么CSS中没有继承

javascript - 处理 Ext.Button 处理程序时更改光标样式

html - flexbox 在 firefox 和 chrome 中的行为不一致?