Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically centering an image with max-height and max-width

Tags:

html

css

I have the following html code:

<div style="border: 3px coral solid;width:400px;height:400px;background:#D4D0C8;">
    <img style="max-width:400px;max-height:400px;" src="myImage.jpg">
</div>

Using these styles images with a width > 400 pixels are resized but remain at the top of the div. Is there some way to vertically center them?

like image 834
James P. Avatar asked Jul 09 '11 14:07

James P.


People also ask

How do I center an image in a span vertically?

Approach: Create a div tag to place the images. In the <img> tag, provide the path of the images using the src attribute and an alternative text using the alt attribute. Add CSS properties to display the images in a vertical alignment.

How do I center my vertical content?

To center both vertically and horizontally, use padding and text-align: center : I am vertically and horizontally centered.

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.


1 Answers

CSS:

div {
    border: 3px solid coral;
    width: 400px;
    height: 400px;
    background: #d4d0c8;
    line-height: 400px;
    text-align: center;
}
img {
    max-width:400px;
    max-height:400px;
    vertical-align: middle;
}

See demo fiddle.

like image 59
NGLN Avatar answered Nov 15 '22 19:11

NGLN