我正在尝试使用 flexbox (display:flex
) 将两个 div
元素并排居中。
左侧的第一个 div
元素只有一个图像。
右侧的第二个 div
元素具有未指定长度的左对齐内联文本。
当文本行短到可以放在一行中时,两个 div 都按我的预期对齐并对齐到中心。
当文本行足够长可以换行时,第二个 div
元素不会像我预期的那样将内容换行。相反,它会在 div
的右侧留下一个大的空白区域。
我在这里模拟了一个例子:http://codepen.io/anon/pen/NGqYQX?editors=110 .改变浏览器窗口的宽度以了解我的意思。
如何将第二个 div
元素设置为缩小自身以适合文本,以便两个 div
元素都居中显示?
.flexbox-container {
display: flex;
justify-content: center;
align-items: center;
}
.div1 {
margin-right: 30px;
}
.div2 {
font-size: 48px;
line-height: 48px;
text-align: left;
}
<div class="flexbox-container">
<div class="div1">
<img src="http://dreamatico.com/data_images/kitten/kitten-2.jpg" width="150px">
</div>
<div class="div2">
This is an example of a line of text.
</div>
</div>
<br>
<div class="flexbox-container">
<div class="div1">
<img src="http://dreamatico.com/data_images/kitten/kitten-2.jpg" width="150px">
</div>
<div class="div2">
This is an example of a much loooooooooooooonger line of text.
</div>
</div>
这是一个 Photoshop 模型,展示了我正在尝试做的事情:
为了实现您的目标(在您的第二张图片中指定),我们需要对您的 HTML 和 CSS 进行一些调整。一切都可以用 flexbox 来完成。
HTML
<div id="flex-container-main">
<div class="flex-container-child">
<figure>
<img src="http://dreamatico.com/data_images/kitten/kitten-2.jpg" width="150px">
</figure>
<p>This is an example of a line of text.</p>
</div>
<div class="flex-container-child">
<figure>
<img src="http://dreamatico.com/data_images/kitten/kitten-2.jpg" width="150px">
</figure>
<p>This is an example of a much loooooooooooooonger line of text.</p>
</div>
</div><!-- end #flex-container-main -->
CSS
#flex-container-main {
display: flex;
flex-direction: column;
align-items: center;
}
.flex-container-child {
display: flex;
align-items: center;
min-height: 127px;
width: 75%;
margin: 10px;
}
figure {
margin: 0 20px 0 0;
}
img {
width: 150px;
height: 127px;
vertical-align: bottom;
}
p {
font-size: 48px;
margin: 0;
}
这是正在发生的事情......
您的问题是:
Keeping flexbox centered when text wraps to 2 or more lines
I am trying to center two div elements side by side in a row with flexbox (display:flex
).
让我们快速浏览一下您的两张图片。
图片 1
图 2
在图 1 中,所有 flex 元素实际上都居中。 Chrome Dev Tools 中的蓝色突出显示强调了这一点。每个元素都完美地位于屏幕中央。
是的,当您将屏幕尺寸调整得更小时,它确实会变得有点笨拙——主要是因为字体较大——但 flex 元素仍然保持居中。
在图 2 中, flex 元素没有均匀居中。您在模型中创建的内容更像是包含两个 flexbox 的列,并且列 居中。但单独来看,只有第一行位于屏幕中央。
关于您的代码的一些注意事项:
- 与
justify-content
在 flex 容器上声明,您将 flex 元素居中。 flex 容器本身不居中。
- 因为两个 flexbox 都是
<body>
的直接子节点, 和 <body>
没有定义的宽度,flexboxes 会根据视口(viewport)自行对齐。
因此,为了达到您想要的效果,我们可以将所有现有标记包装在一个新的 flex 容器 (#flex-container-main
) 中。这会将原始的 flex 容器转换为 flex 元素,然后它们可以作为一个组均匀居中。
新的 flex 元素(现在分类为 .flex-container-child
)被赋予宽度以创建空间和基于图像高度的最小高度。每个 flex 元素也被声明为 flex parent ( display: flex
),这允许我们在子元素上使用 flex 属性。特别是,这对于垂直居中文本很有用(如图像所示)。
(请注意,我对 HTML 语义元素的使用并不是代码工作所必需的。如果您更喜欢原始的 div
标签,只需将它们换回来。重要的调整是新的父容器。)
最后(这对您的布局可能并不重要,但以防万一),浏览器通常会在图像的底部边框下方留出一小段空白。这用于容纳 descenders。与 vertical-align: bottom
, 这个空格被删除了。 (有关详细信息,请参阅 my answer about descenders。)