Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an image center (vertically & horizontally) inside a bigger div [duplicate]

Tags:

html

css

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..

like image 931
Shameem Avatar asked Dec 23 '08 04:12

Shameem


People also ask

How do I center an image vertically in HTML?

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.

How do you center an object vertically?

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.

How do you centralize an image?

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.


2 Answers

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; } 
like image 150
Jonathan Argentiero Avatar answered Oct 09 '22 23:10

Jonathan Argentiero


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.

like image 24
bochgoch Avatar answered Oct 09 '22 22:10

bochgoch