CSS same height as Parent

2019-08-03 15:57发布

问题:

So I have an image that needs a hover effect;

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; 
 }

As you can see, the height of .data is the same as the image. How can I make .overlay the same height of .data?

回答1:

Since the element is an overlay (as the name implies), i'd suggest relatively positioning the parent and then absolutely positioning the overlay relative to it:

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);
}