我对这段代码中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;
}


See fiddle.

或者,如果图像元素具有动态的非静态高度,则可能要考虑其他方法。您可以使用(1)按-50%转换的方法,或(2)flexbox的方法。

对于-50%的转换方法,这是通过将所有四个基数值都设置为0来简单地强制将父容器.divB拉伸为其包装父容器的大小而起作用的。此后,我们将内部子容器放置50 %从顶部开始,然后将其垂直向上偏移其高度的一半,这时将发生-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;
}


See alternative solution #1.



对于flexbox方法,我们重复第一个解决方案中的第一步(将所有基本偏移设置为0),然后简单地使用flexbox规范,并使用align-items: center将内部元素与垂直中心对齐:

.divB {
    display: flex;
    align-items: center;
    position: absolute;
    top: 0px;
    left: 0px;
    bottom: 0px;
    right: 0px;
}


See alternative solution #2.

关于html - 高度元素错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31742854/

10-12 00:21
查看更多