Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize <img/> using absolute positioning

div#ipsko changes width and height to satisfy absolute positioning. Why img#utas doesn't?

JSFiddle: http://jsfiddle.net/pejh7/1/

HTML code:

<div id="upsko">
    <img id="utas" src="http://kharg.czystybeton.pl/108.png" />
    <div id="ipsko"></div>
</div>

CSS code:

div#upsko {
    position: relative;
    top: 200px; left: 200px; width: 100px; height: 100px;
    background: rgba(255,0,0,0.5);
}

img#utas {
    position: absolute;
    top: 10px; left: 10px; right: 10px; bottom: 10px;
}

div#ipsko {
    position: absolute;
    top: 0; left: 0; bottom: 0; right: 0;
    background: rgba(0,255,0,0.5);
}
like image 238
Karol Maciaszek Avatar asked Oct 24 '25 19:10

Karol Maciaszek


2 Answers

Put the img tag in a div, give the image 100% width and height, and then absolute position the container div, e.g.

HTML:

<div id="upsko">
    <div id="utas">
        <img src="http://kharg.czystybeton.pl/108.png" />
     </div>
    <div id="ipsko"></div>
</div>

CSS:

#upsko {
    position: relative;
    top: 200px; left: 200px; width: 100px; height: 100px;
    background: rgba(255,0,0,0.5);
}

#utas {
    position: absolute;
    top: 10px; left: 10px; right: 10px; bottom: 10px;
}
#utas img { height: 100%; width: 100%; }

#ipsko {
    position: absolute;
    top: 0; left: 0; bottom: 0; right: 0;
    background: rgba(0,255,0,0.5);
}

Fiddle

The issues you describe are cause by the image width being unspecified (as other answers have stated) unfortunately without stating a px value for the image size (or converting the top/left/bottom/right and height+width to %) there's no way around this without adding an extra div.

I know adding extra div's is generally considered bad practice, but when it gives you flexibility as above, I think it's generally fine to do.

like image 58
Sean Avatar answered Oct 26 '25 10:10

Sean


see the the div "div#ipsko" does not has its own height and width so it inherit its parent height and width . But the image has its own height and width . so you have to specify the height and width of image to make in fit in the div.

img#utas {
    position: absolute;
    top: 0px;
    left: 0px;
    right: 0px;
    bottom: 0px;
    width: 100%;
    height: 100%;
}
like image 35
ap.singh Avatar answered Oct 26 '25 10:10

ap.singh