Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center image in a div horizontally and vertically

Tags:

html

css

image

I have the following markup code in my page:

<div id="root_img" style="width:100%;height:100%">
    <div id="id_immagine" align="center" style="width: 100%; height: 100%;">
        <a id="a_img_id" href="./css/imgs/mancante.jpg">
            <img id="img_id" src="./css/imgs/mancante.jpg" />
        </a>
    </div>
</div>

And it does not appear as I expected, it looks like that:

enter image description here

But I wanted to get this result:

enter image description here

How can I center this image horizontally and vertically?

like image 622
CeccoCQ Avatar asked Apr 24 '12 10:04

CeccoCQ


People also ask

How do you center a div both vertically and horizontally?

You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.

How do I center an object horizontally in a div?

To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.


2 Answers

Here is a tutorial for how to center the images vertically and horizontally in a div.

Here is what you are looking for:

.wraptocenter {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
  width: 200px;
  height: 200px;
  background-color: #999;
}
.wraptocenter * {
  vertical-align: middle;
}
<div class="wraptocenter">
  <img src="http://www.brunildo.org/thumb/tmiri2_o.jpg">
</div>
like image 106
AlphaMale Avatar answered Sep 16 '22 22:09

AlphaMale


For vertical alignment, I would include some CSS to position it from the top 50% and then move it up half the number of pixels height of the image.

Horizontal, I would use a margin, as suggested.

So if your image was 100x100px you'd end up with.

<img id="my_image" src="example.jpg">

<style>
#my_image{
 position: absolute;
 top: 50%;
 margin: -50px auto 0;
}
</style>
like image 32
David Yell Avatar answered Sep 20 '22 22:09

David Yell