html - 第一个和最后一个 flexbox 框的边距

标签 html css flexbox

我希望所有 flexbox 盒子的左侧和右侧始终具有相同的空间距离。目前我有这段代码:

body
  background-color white
  margin 0 0
  padding 0 0

.overlay
  display flex
  position absolute
  background-color grey
  cursor pointer
  color #8e3433
  flex-flow row nowrap
  justify-content flex-start
  height 40vh
  width 100vw
  bottom 0
  left 0
  margin 0
  overflow-y hidden
  overflow-x scroll

.overlay .item-image
  border-radius 5px
  flex 1 1 auto
  min-width 45.0vw
  width 45.0vw
  margin 0 2vw 0 2vw
  border 1px solid yellow

请参阅this以 fiddle 为例(如果它没有立即显示,你必须在最后选择样式代码,然后按回车键(JSbin 中的一个错误......)它应该会显示出来)。

第一个框 的左侧,我得到 2vh 而不是 4vh。看: enter image description here 在其他盒子之间一切都很好(4vh)。 最后一个框 的右侧没有任何空间。看: enter image description here 所以我的问题: 1) 如何获取第一个框左侧的 4vh?;和 2) 如何得到最后一个方框右边的4vh?

我尝试查找它并看到使用容器填充解决略有不同问题的解决方案。我更喜欢不调整容器填充的解决方案。

最佳答案

更新的答案

使用伪元素作为flex item来占用空间:

ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
  display: flex;
  height: 300px;
  overflow-x: auto;
  width: 600px;
  background: orange;
}
li {
  margin-left: 30px;
  background: blue;
  color: #fff;
  padding: 90px;
  white-space: nowrap;
  flex-basis: auto;
}
ul::after {
  content: "";
  flex: 0 0 30px;
}
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
</ul>


上一个答案

注意:由于框被“过度约束”,下面的解决方案可能不起作用(参见: How can I stop the last margin collapsing in flexbox? )

每个框的左右边距为 2vw。

所以边距空间将是第一个元素的一半(没有右边距,因为没有前一个框)和最后一个元素的一半(没有左边距,因为没有额外的框)。

相反,试试这个:

.item-image { margin-left: 4vw }
.item-image:last-child { margin-right: 4w }

关于html - 第一个和最后一个 flexbox 框的边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41936592/

相关文章:

html - 尽管背景颜色发生变化,但无法更改列表菜单悬停和事件文本颜色

html - 为什么 flex-wrap : wrap not work on safari

jquery - 选择单选按钮时更改背景颜色

javascript - 当达到 0 时停止倒计时

html - 如何在 <ul> 开始之前删除此换行符?

html - 显示 flex 的回退

html - <a> 元素内的文本位置

javascript - 在 cytoscape.js 中通过 cy.add() 添加多条边后使用 mapData()

css - 是否可以对重复和可包装的 CSS 网格中的列使用固定的最小和最大宽度?

css - flex 元素是 block 级元素吗?