Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change width and height of an absolute positioned image placed in a div by css :before [duplicate]

Tags:

html

css

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>
like image 876
Godzilla Avatar asked Apr 21 '14 12:04

Godzilla


People also ask

How do I resize and position an image in CSS?

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.

Why does position absolute affect width?

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.


1 Answers

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;
}
like image 52
web-tiki Avatar answered Nov 05 '22 23:11

web-tiki