繁体   English   中英

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

[英]CSS position absolute and height 100% issue on 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中使用它吗?

有时需要给容器元素包装一个绝对元素, 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; } 

似乎在同时position:absolutedisplay:table情况下,Chrome没有应用height:100% ,当然在包装上也设置了position:relative

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

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

按照这篇文章查找水平和垂直居中的更多方法。

片段

 .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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM