我对这段代码中 div.divB
元素的高度有疑问:
<div class="divA">
<img src="http://lorempixel.com/1000/130"/>
<div class="divB">
<span>Text text</span>
</div>
</div>
参见 this jsfiddle .
为什么我的是div.divB.height != div.divA.height
?但是他的高度是100%。
我想要它,以便“文本文本”位于中间。
编辑:
高度图像是随机的,因为图像文件是由用户上传的。在此示例中,我使用 130,但可以是 200 或 50。
最佳答案
那是因为你声明表格的高度为100px,比图片的高度少了30px。如果将该值更新为 130px,它应该会按预期工作:
.divB{
display: table;
width: 100%;
height: 130px;
position: absolute;
top: 0px;
left: 0px;
}
或者,如果您的图像元素具有动态的非静态高度,您可能需要考虑其他方法。您可以使用 (1) translate by -50% 方法,或 (2) flexbox 方法。
对于按 -50% 进行翻译的方法,通过将所有四个基本值设置为 0,将父容器 .divB
强行拉伸(stretch)到其包装父容器的大小即可。也就是说,我们将内部子节点定位在距离顶部 50% 的位置,然后将其垂直向上偏移其高度的一半——这就是 translate by -50% 技巧开始的时候:
.divB{
position: absolute;
top: 0px;
left: 0px;
bottom: 0px;
right: 0px;
}
.divB > span{
display: block;
transform: translateY(-50%);
padding-left: 120px;
position: absolute;
top: 50%;
font-size: 1.8rem;
color:white;
}
对于 flexbox 方法,我们重复第一个解决方案中的第一步——将所有基数偏移设置为 0——然后简单地使用 flexbox 规范并使用 align-items 将内部元素对齐到垂直中心:中心
:
.divB {
display: flex;
align-items: center;
position: absolute;
top: 0px;
left: 0px;
bottom: 0px;
right: 0px;
}
关于html - 错误的高度元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31742854/