Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to vertically center an image inside of a div element in HTML using CSS?

Tags:

css

I have a markup like this:

<div>   <img /> </div> 

The div is higher than img:

div {   height: 100px; }  img {   height: dynamic-value-smaller-than-100px; } 

I need the image to be in the middle of the div (have same amout of white space above and below it).

I tried this and it does not work:

div {   vertical-align: middle; } 
like image 205
Josef Sábl Avatar asked Feb 10 '10 14:02

Josef Sábl


People also ask

How do I vertically align an image in HTML?

Answer: Use the CSS vertical-align Property You can align an image vertically center inside a <div> by using the CSS vertical-align property in combination with the display: table-cell; on the containing div element.

How do I center content vertically in a div?

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 you center an object vertically in CSS?

You can just set text-align to center for an inline element, and margin: 0 auto would do it for a block-level element.

How do I vertically align text and image in CSS?

We need to create a parent element that contain both image and text. After declaring the parent element as flexbox using display: flex; we can align the items to the center using align-items: center;. Example: This example uses flexbox to vertically align text next to an image using CSS.


1 Answers

if your image is purely decorative, then it might be a more semantic solution to use it as a background-image. You can then specify the position of the background

background-position: center center; 

If it is not decorative and constitutes valuable information then the img tag is justified. What you need to do in such case is style the containing div with the following properties:

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

Read more about this technique here. Reported to not work on IE6/7 (works on IE8).

like image 102
pixeline Avatar answered Sep 24 '22 10:09

pixeline