chicharito
chicharito

Reputation: 1087

Div Vertically aligning an image

I have a div with image "image.jpg".

By using text-align=center, the image is being centered horizontally.

However it's not vertically aligned. How would I implement the vertical alignment?

<div style="vertical-align: middle;text-align:center;">
    <img title="Title3" src="image.jpg" style="display: inline;" id="idImage">
</div>

Upvotes: 0

Views: 138

Answers (3)

Jake Long
Jake Long

Reputation: 706

If you set the height of the parent container and set your margin-top: auto, it should align to the middle I think. This works with horizontally aligning, but I haven't tried with vertical. Anyways, it would avoid absolute positioning

As mentioned before, you can also use javascript to find the height, then set the margin, something like this:

var image = document.getElementById("myImage");
var imgHeight = image.style.height;
image.style.marginTop = -(imgHeight/2);
image.style.top = 50%; //you can probably just set this in css and omit this line

you must of course set

#myImage{
  position: absolute;
}

though

Upvotes: 0

Roddy of the Frozen Peas
Roddy of the Frozen Peas

Reputation: 15180

Use the vertical-align property as described in this article. Note that in order to get vertical-align to work you need to do display: table-cell as well.

div.centered {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    /* other styling */
}

Where I've given your <div> the class name of centered.

Also you shouldn't use text-align for centering, but instead add margin: 0 auto; to the image styling.

EDIT

HTML:

<div class="centered">
    <img src="..." class="centered-image" />
</div>

CSS:

div.centered {
    display: table-cell;
    vertical-align: middle;
}

img.centered-image {
    margin: 0 auto;
}

Upvotes: 1

idrumgood
idrumgood

Reputation: 4924

You have to know the dimensions for this to work (or use javascript to get the dimensions if you'll have different ones). This will also center the image horizontally (so you don't need your text-align=center )

Taken from css-tricks

.center {
   width: 300px;
   height: 300px;
   position: absolute;
   left: 50%;
   top: 50%; 
   margin-left: -150px;
   margin-top: -150px;
}

height and width are that of the image in question and the top and left margins are set at half the respective height and width.

Upvotes: 0

Related Questions