CSS与Parent相同的高度

时间:2015-01-22 03:35:56

标签: html css image height

所以我的图片需要hover效果;

HTML

 <div class="data">
    <img src="http://scontent-a-dfw.cdninstagram.com/hphotos-xpa1/t51.2885-15/e15/10809512_341410899374744_4010362_n.jpg"/>

    <div class="overlay"></div>
 </div>

CSS

 .data {
    width: 100px; 
    margin: auto; 
    padding: 5px; 
    height: auto; 
 }
 img {
    width: 100%; 
 }
 .overlay {
    width: 100%; 
    height: ___?; 
    background-color: blue; 
 }

如您所见,.data的高度与图像相同。如何使.overlayheight相同.data

1 个答案:

答案 0 :(得分:4)

由于元素是叠加层(顾名思义),我建议相对定位父级,然后将叠加层 relative 绝对定位到它:

Example Here

.data {
    width: 95%;
    margin: auto;
    position: relative;
}
.data .overlay {
    position: absolute;
    top: 0; right: 0;
    bottom: 0; left: 0;
}
.data:hover .overlay {
    background: rgba(0, 0, 0, .5);
}