6

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>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Godzilla
  • 99
  • 7

2 Answers2

2

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;
}
web-tiki
  • 99,765
  • 32
  • 217
  • 249
0

You cannot change the dimensions of the image when inserted this way. As others have mentioned, you may use background-image on the generated content instead.

Daze
  • 478
  • 5
  • 17