我有一个 Div1,Div1 里面有一个 Div2。
Div2 中有图像和可变长度的文本,我想将 Div2 的宽度保持为自动并将其居中放置在 Div1 中。
如下所述:
+-------------------------------------------------------------------+
| Div1 |
| +-------+--------------------+ |
| | Image | Some Test Text | <- Div2: Width:auto; |
| +-------+--------------------+ |
| |
+-------------------------------------------------------------------+
我正在尝试创建它,但面临将背景 Div 覆盖到文本和图像的问题,实际上我想将 Div 高度和宽度保持为自动,但它没有按预期工作:
最佳答案
如果我没有正确理解你的问题,你应该使用 css3 flexbox
为此。
.text-and-image-holder {
justify-content: center;
align-items: center;
display: flex;
}
上面的 css 将创建以下布局,正如您在工作代码段中看到的那样,文本和图像将相互垂直居中对齐:
+---------------------------------------+
| | Lorem ipsum dolor sit |
| | amet, lorem ipsum dolor |
| | sit amet, lorem ipsum |
| <img> | dolor sit amet, lorem |
| | ipsum dolor sit amet, |
| | lorem ipsum dolor sit |
| | amet, lorem ipsum |
+---------------------------------------+
.image-style {
margin-right: 20px;
}
.text-style {
font-size: 15px;
}
.text-and-image-holder {
justify-content: center;
align-items: center;
margin-bottom: 20px;
background: red;
padding: 20px;
display: flex;
}
<div class="text-and-image-holder">
<img src="http://placehold.it/30x30" class="image-style">
<div class="text-style">Vertically Center Text Here</div>
</div>
<div class="text-and-image-holder">
<img src="http://placehold.it/30x30" class="image-style">
<div class="text-style">Very long text Vertically Center Here and lorem ipsum dolor sit amet.</div>
</div>
关于html - 在 Div 内居中 Div,宽度为自动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40505931/