Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center the image of unknown size inside div?

Assume that I have a div having the following styles:

#container {
    position: fixed;
    width: 100%;
    height: 100%;
}

Also I have an image of unknown size (the size may vary), which I want to align both vertically and horizontally.

What is the best way of doing that?

like image 895
Andrey Ozornin Avatar asked Sep 08 '10 16:09

Andrey Ozornin


People also ask

How do I center an image in a div?

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 I fix an image in a specific div?

To auto-resize an image or a video to fit in a div container use object-fit property. It is used to specify how an image or video fits in the container. object-fit property: This property is used to specify how an image or video resize and fit the container.

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.

How do I force a div to center?

Simply add text-align center to parent div and set the child div display to inline-block. This will force our div to behave like inline element and therefore subjected text-align center.


2 Answers

The background image method will work, with background-position:center center, unfortunately you'll lose control of scaling your image.

You can set your image as follows:

position:absolute;
margin:auto;
top:0;
bottom:0;
left:0;
right:0;

PS. Keep in mind that this will be centered relative to its closest positioned parent.

like image 171
Benn Wolfe Avatar answered Oct 19 '22 22:10

Benn Wolfe


Add the following:

The first two lines center it vertically, the last horizontally.

display: table-cell;
vertical-align: middle ;
text-align: center;

more info can be found here: http://www.w3.org/Style/Examples/007/center

like image 45
David Avatar answered Oct 19 '22 22:10

David