css 如何调整单个弹性框项(改写调整内容)[重复]

s4n0splo  于 2022-12-15  发布在  其他
关注(0)|答案(6)|浏览(137)

此问题在此处已有答案

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?(6个答案)
去年关闭了。
对于弹性物料,您可以使用align-self覆盖align-items。我正在寻找一种方法来覆盖弹性物料的justify-content
如果您有一个带有justify-content:flex-end的flexbox容器,但您希望第一个项目是justify-content: flex-start,该如何完成呢?

3lxsmp7m

3lxsmp7m1#

看起来没有justify-self,但是您可以通过将margin设置为auto ¹来实现类似的结果。例如,对于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;
}

个字符
¹此行为由Flexbox规范定义。

093gszye

093gszye2#

AFAIK在规格中没有属性,但这里有一个我一直在使用的技巧:将容器元素(display:flex)设置为justify-content:space-around然后在第一个和第二个项目之间添加一个额外的元素,并将其设置为flex-grow:10(或与您的设置一起工作的其他值)
编辑:如果条目紧密对齐,最好也在extra元素中添加flex-shrink: 10;,这样布局在较小的设备上也能正确响应。

a7qyws3x

a7qyws3x3#

如果实际上没有限制将所有这些元素作为兄弟节点,则可以将一起出现的元素 Package 在另一个默认flex框中,并让这两个元素的容器使用空格。

.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容器和lone child的顺序。

eh57zj3b

eh57zj3b4#

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

ergxz8rk

ergxz8rk5#

对于那些您确实希望flex-end的项目宽度已知的情况,您可以将其flex设置为“0 0 ##px”,并将您希望flex-start的项目设置为flex:1
这将导致伪flex-start项填充容器,只需将其格式化为text-align:left或其他格式即可。

k2arahey

k2arahey6#

要扩展Pavlo的答案https://stackoverflow.com/a/34063808/1069914,您可以在其行为中具有多个子项justify-content: flex-start,但具有最后一个项justify-content: flex-end

.container {
  height: 100px;
  border: solid 10px skyblue;
  display: flex;
  justify-content: flex-end;
}

.container > *:not(:last-child) {
    margin-right: 0;
    margin-left: 0;
}

/* set the second to last-child */
.container > :nth-last-child(2) {
    margin-right: auto;
    margin-left: 0;
}

.block {
  width: 50px;
  background: tomato;
  border: 1px solid black;
}
<div class="container">
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block" style="width:150px">I should be at the end of the flex container (i.e. justify-content: flex-end)</div>
</div>

相关问题