除单个项目的行外,Flexbox之间是否有空格?

时间:2019-06-07 05:54:13

标签: html css flexbox

我有两个div。一个需要坐在左边,一个应该坐在右边。带有justify-content: space-between的父级flexbox可以很好地解决此问题,除非flex项包装时(它们应该能够这样做)。包裹后,它们将向左对齐,因为总共只有两项。

如何使单个项目的行居中对齐?

<div style="display: flex; justify-content: space-between; flex-wrap: wrap">
	<div style="background: orange">
		<strong>Canvas Prints</strong><br>
		<span style="font-size: 14px; color: #ff0000">Create a masterpiece for any wall in your home!</span>
	</div>
	<div style="background: pink">
		<img width="176" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTEAPU9xK-mE81DSwYqh_uMb_EUuqXT1yWzIvs9j7diGY-FHh6X">
	</div>
</div>

(或您可以使用小提琴,因为挤压小提琴的输出窗格比调整整个SO窗口的大小以查看div包更容易:https://jsfiddle.net/xv6oa418/1/


附加说明::@ KaranTewari建议在第一个子div上添加flex: 1,但我希望左侧div中的文本在绝对必要之前不要换行(特别是,它应该开始仅在第二个flex项目包装到下一行之后包装)。第二个div实际上将是一个图像,因此我更新了小提琴和摘录以反映这一点。

3 个答案:

答案 0 :(得分:2)

我自己弄清楚了。我在第一个/左div上使用了flex-grow: 1,在第二个/右div上使用了margin: auto。这会使第一个div扩展为占据所有空间,因此第二个div的自动边距不会执行任何操作。然后,当它自动换行时,第二个div不再被第一个div阻塞,并且自动边距接管,将第二个div居中。

像这样:

<div style="display: flex; justify-content: space-between; flex-wrap: wrap">
	<div style="background: orange; flex-grow: 1;">
		<strong>Canvas Prints</strong><br>
		<span style="font-size: 14px; color: #ff0000">Create a masterpiece for any wall in your home!</span>
	</div>
	<div style="background: pink; margin: auto">
		<img width="176" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTEAPU9xK-mE81DSwYqh_uMb_EUuqXT1yWzIvs9j7diGY-FHh6X">
	</div>
</div>

(小提琴:https://jsfiddle.net/xv6oa418/2/

答案 1 :(得分:0)

.parent {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}


.text {
  background: orange;
  padding:10px;
  border-radius:10px;

}

.text:only-child {
  background-color: green;
  margin:0 auto;
}
<div class="parent">
  <div class="text">
    <strong>Canvas Prints</strong><br>
    <span >Create a masterpiece for any wall in your home!</span>
  </div>
  <div class="img" >
    <img width="176" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTEAPU9xK-mE81DSwYqh_uMb_EUuqXT1yWzIvs9j7diGY-FHh6X">
  </div>
</div>

您可以使用:only-child选择器,并将margin:auto分配给only-child元素。请查看代码段。

答案 2 :(得分:-1)

尝试使用

flex:1

这可以确保您使用的是可用空间,在此已对jsfiddle进行了编辑 https://jsfiddle.net/karantewari/tfg0kymb/1/