I have a div 200 x 200 px. I want to place a 50 x 50 px image right in the middle of the div.
How can it be done?
I am able to get it centered horizontally by using text-align: center
for the div. But vertical alignment is the issue..
I have a div 200 x 200 px. I want to place a 50 x 50 px image right in the middle of the div.
How can it be done?
I am able to get it centered horizontally by using text-align: center
for the div. But vertical alignment is the issue..
easy
Related: Center a image
I had this issue in HTML5 using CSS3 and my image was centered as such within the DIV... oh yes, I can't forget how I had to add the height to show the image... for a while I wondered where it was until I did this. I don't think the position and display are necessary.
You can center an image horizontally and vertically with the code below (works in IE/FF). It will put the top edge of the image at exactly 50% of the browser height, and the margin-top(pulling half the height of the image up) will center it perfectly.
I would set your larger div with
position:relative;
then for your image do this:This only works because you know the dimensions of both the image and the containing div. This will also let you have other items within the containing div... where solutions like using line-height will not.
EDIT: Note... your margins are negative half of the size of the image.
Another way (not mentioned here yet) is with Flexbox.
Just set the following rules on the container
div
:FIDDLE
A good place to start with Flexbox to see some of it's features and get syntax for maximum browser support is flexyboxes
Also, browser support nowadays is quite good: caniuse
For cross-browser compatibility for
display: flex
andalign-items
, you can use the following: