首页 文章

如何证明单个flexbox项目的合理性(覆盖justify-content)

提问于
浏览
175

您可以使用 align-self 覆盖 align-items 作为弹性项目 . 我正在寻找一种方法来覆盖 justify-content 的Flex项目 .

如果你有一个带有 justify-content:flex-end 的flexbox容器,但你希望第一个项目是 justify-content: flex-start ,那该怎么办呢?

这篇文章最好回答:https://stackoverflow.com/a/33856609/269396

6 回答

  • 334

    似乎没有 justify-self ,但你可以达到类似的结果设置 marginauto ¹ . E. g . 对于 flex-direction: row (默认),您应该设置 margin-right: auto 以将子项对齐到左侧 .

    .container {
      height: 100px;
      border: solid 10px skyblue;
      
      display: flex;
      justify-content: flex-end;
    }
    .block {
      width: 50px;
      background: tomato;
    }
    .justify-start {
      margin-right: auto;
    }
    
    <div class="container">
      <div class="block justify-start"></div>
      <div class="block"></div>
    </div>
    

    ¹此行为是defined by the Flexbox spec .

  • 1

    AFAIK在规范中没有属性,但是这里是我一直在使用的技巧:将容器元素(带有 display:flex 的那个)设置为 justify-content:space-around 然后在第一个和第二个项目之间添加一个额外的元素并将其设置为 flex-grow:10 (或与您的设置一起使用的其他一些值)

    编辑:如果项目紧密对齐,最好将 flex-shrink: 10; 添加到额外元素,这样布局将在较小的设备上正确响应 .

  • 10

    如果您实际上并不局限于将所有这些元素保留为兄弟节点,则可以将其中的元素包装在另一个默认弹性框中,并使两者的容器之间使用空格 .

    .space-between {
      border: 1px solid red;
      display: flex;
      justify-content: space-between;
    }
    .default-flex {
      border: 1px solid blue;
      display: flex;
    }
    .child {
      width: 100px;
      height: 100px;
      border: 1px solid;
    }
    
    <div class="space-between">
      <div class="child">1</div>
      <div class="default-flex">
        <div class="child">2</div>
        <div class="child">3</div>
        <div class="child">4</div>
        <div class="child">5</div>
      </div>
    </div>
    

    或者如果你使用flex-start和flex-end反转做同样的事情,你只需要交换default-flex容器和孤独子的顺序 .

  • 0

    It seems like justify-self is coming to browsers soon . MDN上已有一篇文章 . 在撰写本文时,浏览器支持很差 .

    关于保证金解决方案:我有一个有差距的Flexbox网格 . Flexbox没有 flex-gap 属性(还有?) . 所以对于排水沟,我使用填充和边距,所以 margin: auto 需要覆盖其他边距...

  • 0

    对于您想要知道的项目宽度的情况,您可以将其flex设置为"0 0 ##px"并使用 flex:1 设置您想要的项目 flex-start

    这将导致伪 flex-start 项目填充容器,只需将其格式化为 text-align:left 或其他 .

  • 16

    我通过将内部项的样式设置为 margin: 0 auto 来解决了类似的情况 .
    情况:我的菜单通常包含三个按钮,在这种情况下,它们必须是 justify-content: space-between . 但是当只有一个按钮时,它现在将居中对齐而不是向左 .

相关问题