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..
Step 1: Wrap the image in a div element. Step 2: Set the display property to "flex," which tells the browser that the div is the parent container and the image is a flex item. Step 3: Set the justify-content property to "center." Step 4: Set the width of the image to a fixed length value.
For vertical alignment, set the parent element's width / height to 100% and add display: table . Then for the child element, change the display to table-cell and add vertical-align: middle . For horizontal centering, you could either add text-align: center to center the text and any other inline children elements.
To center an image with CSS Grid, wrap the image in a container div element and give it a display of grid . Then set the place-items property to center. P.S.: place-items with a value of center centers anything horizontally and vertically.
Working in old browsers (IE >= 8)
Absolute position in combination with automatic margin permits to center an element horizontally and vertically. The element position could be based on a parent element position using relative positioning. View Result
img { position: absolute; margin: auto; top: 0; left: 0; right: 0; bottom: 0; }
Personally, I'd place it as the background image within the div, the CSS for that being:
#demo { background: url(bg_apple_little.gif) no-repeat center center; height: 200px; width: 200px; }
(Assumes a div with id="demo"
as you are already specifying height
and width
adding a background
shouldn't be an issue)
Let the browser take the strain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With