July 31, 200917 yr Hey guys, Having a bit of an issue - how can I center an image inside a div? I'm talking so it sits exactly in the middle both horizontally and vertically...? Any help much appreciated
July 31, 200917 yr #container { position: relative; width: 400px; height: 300px; } #image { width: 200px; height: 100px; position: absolute; top: 50%; margin-top: -50px; left: 50%; margin-left: -100px; } <div id="container"> <img id="image" src="image.jpg" alt="description"> </div> The widths and heights are whatever you want but the position: relative, position: absolute, left: 50%; top: 50% and margins are critical; negative margins are always half the width and height of the image.
August 3, 200917 yr Does specifying the width and height of image neccesary or it's an additional markup...
August 3, 200917 yr No, you don't have to state the size the image with width and height if it's already the correct size, but the negative margins must be correct for the image size, either for the original image size or the size as defined by width and height.
Create an account or sign in to comment