坏高度元素

时间:2015-07-31 09:34:47

标签: html css css3

我对此代码中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%。 我想要它,以便&#34;文字文字&#34;在中间。

编辑:
高度图像是随机的,因为图像文件是由用户上传的。在这个例子中,我使用130但可以是200或50。

2 个答案:

答案 0 :(得分:2)

这是因为您声明表格的高度为100px,比图像的高度小30px。如果您将该值更新为130px,它应该按预期工作:

.divB{
    display: table;
    width: 100%;
    height: 130px;
    position: absolute;
    top: 0px;
    left: 0px;
}

See fiddle.

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

对于-50%的翻译方法,只需将父容器.divB强制拉伸到其包装父级的大小,方法是将所有四个基数值设置为0.之后,我们定位内心的孩子从顶部开始的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将内部元素与垂直中心对齐:< / p>

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

See alternative solution #2.

答案 1 :(得分:0)

首先,divA仍然设置为阻止,因此虽然它可能只有1000像素宽的图像,但它将继续比该图像更宽,将元素设置为display: inline-block将有助于制作确保它的宽度设置得很好。

接下来,您需要将divB的高度设置为与divA相同。在这种情况下,它的130px。

当你真正使用text-align: center;能力时,你也使用填充来使文本居中。

以下是完整示例

.divA {
  position: relative;
  display: inline-block;
  overflow: auto;
}
.divB {
  display: table;
  width: 100%;
  height: 130px;
  position: absolute;
  top: 0px;
  left: 0px;
}
.divB > span {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
  font-size: 1.8rem;
  color: white;
}
<div class="divA">
  <img src="http://lorempixel.com/1000/130" />
  <div class="divB">
    <span>Text text</span>
  </div>
</div>