Chrome上的CSS位置绝对和高度100%问题

时间:2018-01-20 16:45:56

标签: html css google-chrome

我的问题是100%高度的容器无法在Chrome上运行。 简而言之,它是图像的一个标题,当图像悬停在图像上时出现在图像上。

.item {
  position: relative;
}

.caption {
  width: 100%;
  height: 100%;
  position: absolute;
  background-color: rgba(0, 0, 0, 0.6);
  display: table;
  top: 0;
  left: 0;
  box-sizing: border-box;
  border-radius: 4px;
  opacity: 0;
  transition: 0.2s;
}

a:hover .caption {
  opacity: 1;
  transition: 0.2s;
}

.caption .caption-inter {
  display: table-cell;
  vertical-align: middle;
}

.item img {
  width: 100%;
}
<div class="item">
  <a href="#blabla">
    <img src="//i.stack.imgur.com/tiQ1S.jpg">
    <div class="caption">
      <span class="caption-inter">caption of the image</span>
    </div>
  </a>
</div>

适用于Firefox,IE,但对于Chrome,带背景的标题只显示在图片的顶部。

知道如何让它在Chrome中运行吗?

2 个答案:

答案 0 :(得分:0)

有时需要给容器元素,即包装绝对元素position: relative,以按预期包装绝对元素。

除此之外,您应该将标题更改为display: block,以便它可以合法地应用width: 100%

/* added this */

#blabla {
  /* its important to give the container position: relative,
      when it's wrapping an absolute element */
  position: relative;

  /* It's needed to give the anchor tag "inline-block" attribute so it 
     can receive width and height, since it's an inline element */

  display: inline-block;
}

.caption {
  width: 100%;
  height: 100%;
  position: absolute;
  background-color: rgba(0, 0, 0, 0.6);

  /* changed from table to block */
  display: block;

  top: 0;
  left: 0;
  box-sizing: border-box;
  border-radius: 4px;
  opacity: 0;
  transition: 0.2s;
}

a:hover .caption {
  opacity: 1;
  transition: 0.2s;
}

.caption .caption-inter {
  display: table-cell;
  vertical-align: middle;
  text-overflow: ellipsis;
}

答案 1 :(得分:0)

在同时设置height:100%position:absolute时,Chrome似乎不适用display:table,当然还设置了position:relative包装。

我建议使用flexbox作为标题以便于居中,并使用HTML5语义<figure> + <figcaption>元素进行标记。

.caption {
  ...
  display: flex;
  justify-content: center;
  align-items: center;
}

按照this post查找更多水平和垂直居中方式。

<强>段

.figure {
  position: relative;
  display: inline-block;  /*NEW*/
  margin: 0;              /*NEW*/
}

.image {
  border-radius: 4px;
  width: 100%;
  height: auto;
  display: block;
}

.caption {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  box-sizing: border-box;
  border-radius: 4px;
  opacity: 0;
  transition: 0.2s;
  display: flex;            /*NEW*/
  justify-content: center;  /*NEW*/
  align-items: center;      /*NEW*/
}

a:hover .caption {
  opacity: 1;
}
<a class="item" href="#">
  <figure class="figure">
    <img class="image" src="//i.stack.imgur.com/tiQ1S.jpg">
    <figcaption class="caption">
      caption of the image
    </figcaption>
  </figure>
</a>