Mat*_*dor 7 html css alignment css3 flexbox
我试图div用flexbox(display:flex)将两个元素并排连续居中.
div左边的第一个元素只有一个图像.
div右边的第二个元素具有未指定长度的左对齐内联文本.
当文本行足够短以适合一行时,两个div都按照我的预期对齐并对齐到中心.
当文本行足够长以包裹到两行时,第二个div元素不会像我期望的那样将自己包裹在内容周围.相反,它在右侧留下了一个很大的空白区域div.
我在这里嘲笑了一个例子:http://codepen.io/anon/pen/NGqYQX?edit = 110.改变浏览器窗口的宽度,看看我的意思.
如何设置第二个div元素以缩小自身以适合文本,以便两个div元素都显示为居中?
HTML:
<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>
Run Code Online (Sandbox Code Playgroud)
CSS:
.flexbox-container {
display: flex;
justify-content: center;
align-items: center;
}
.div1 {
margin-right: 30px;
}
.div2 {
font-size: 48px;
line-height: 48px;
text-align: left;
}
Run Code Online (Sandbox Code Playgroud)
这是一个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 -->
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
这是发生了什么......
你的问题问:
当文本换行到2行或更多行时,保持flexbox居中
我试图用flexbox(
display:flex)将两个div元素并排连接.
让我们快速浏览一下你的两张照片.
图片1
图2
在图像1中,所有弹性项目实际上都居中.Chrome Dev Tools的蓝色亮点强调了这一点.每个项目都完美地位于屏幕中心.
是的,当您重新调整屏幕尺寸时,它确实变得有点笨重 - 主要是因为字体较大 - 但是Flex项仍然保持居中.
在图像2中,柔性项目不是均匀居中的.您在模型中创建的内容更像是包含两个Flexbox的列,并且该列居中.但是单独只有第一行以屏幕为中心.
关于代码的几点注意事项:
justify-contentflex容器上声明,您将Flex项目居中.Flex容器本身不居中.<body>,并且<body>没有定义的宽度,因此flexbox会相对于视口对齐.因此,为了达到您想要的效果,我们可以将所有现有标记包装在新的Flex容器中(#flex-container-main).这会将原始的Flex容器转换为弹性项目,然后可以将它们作为一组均匀地居中.
新的弹性项目(现在被归类为.flex-container-child)被赋予宽度以创建空间和基于图像高度的最小高度.每个flex项也被声明为flex parent(display: flex),它允许我们在子元素上使用flex属性.特别是,这对于垂直居中文本非常有用(如图像所示).
(请注意,我不需要使用HTML语义元素来使代码工作.如果您更喜欢原始div代码,只需将它们交换回来.重要的调整是新的父容器.)
最后(这可能对您的布局不重要,但以防万一),浏览器通常会在底部边框下为图像提供一小部分空白.这用于容纳下降器.随着vertical-align: bottom,这个空间被删除.(有关详细信息,请参阅我关于下降器的答案.)