align-self
align-items
justify-content
如果你有一个带有justify-content:flex-end的flexbox容器,但你想让第一项是justify-content: flex-start,该怎么做呢?
justify-content:flex-end
justify-content: flex-start
display:flex
justify-content:space-around
flex-grow:10
编辑:如果项目是紧密对齐的,添加flex-shrink: 10;到额外的元素也是一个好主意,这样布局将在较小的设备上正确响应。
flex-shrink: 10;
对于那些你想要flex-end的项的宽度已知的情况,你可以将它们的flex设置为“0 0 ##px”,并将你想要的项设置为flex-start和flex:1
flex-end
flex-start
flex:1
这将导致伪flex-start项填充容器,只需将其格式化为text-align:left或其他。
text-align:left
似乎没有justify-self,但你可以实现类似的结果设置适当的margin到auto¹。例如,对于flex-direction: row(默认),你应该设置margin-right: auto以使子元素向左对齐。
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; }
<div class="container"> <div class="block justify-start"></div> <div class="block"></div> </div>
¹这个行为是由Flexbox规范定义。
如果您实际上没有限制将所有这些元素都作为兄弟节点保存,您可以将一起使用的元素包装在另一个默认的伸缩盒中,并让两者的容器使用空格。
.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的顺序。
margin: 0 auto
justify-content: space-between
为了扩展Pavlo的答案https://stackoverflow.com/a/34063808/1069914,你可以在它们的行为中有多个子项justify-content: flex-start,但最后一项justify-content: flex-end
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>