I'm trying to place an image in a div using css:before with position:absolute; there is already an image in that div. Why I can't control the height or width of that absolute positioned image?
css:
div:before{
content:url('buble.png');
position:absolute;
left:0;
top:0;
width:100%;
height:auto;
z-index:200;
}
html:
<div><img src="profile_pic.png" alt="" /></div>
We can resize the image by specifying the width and height of an image. A common solution is to use the max-width: 100%; and height: auto; so that large images do not exceed the width of their container. The max-width and max-height properties of CSS works better, but they are not supported in many browsers.
Because the element, which you give absolute position take the width from his parent and didn't behave as a block element. It takes the width and height from its content. And only when the content is relatively positioned.
Explanation :
You won't be able to apply Css properties to the image if you place it in the content of the :before
pseudo element. the width/height
you set apply only to the pseudo element and not on it's content.
Solution :
Set the image as background of the :before
pseudo element. Then you can use background-size
property to size the image as desired.
FIDDLE
As explained in background-size specs, you can use percentages to size the image or values like cover/contain
. You can also position, center horizontaly/verticaly your image using background-position
.
CSS :
div {position:relative;width:350px;}
div:before{
content:"";
position:absolute;
background-image : url('buble.png');
background-size:contain;
width:100%;
height:100%;
z-index:200;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With