Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertical-align middle with display table-cell not working on images

I'm trying to use the vertical-align: middle on a layout to vertically center sometimes text, sometimes images, but it's only working on text. Can anyone tell me why?

HTML:

<div>
    <img src="http://jsfiddle.net/img/logo.png"/>
</div>

<div>
    <span> text </span>
</div>

CSS:

div{
    width:200px;
    height:200px;
    background-color:red;
    display:table;

    margin:10px;
}
img, span{
    display:table-cell;
    vertical-align:middle;
}

http://jsfiddle.net/9uD8M/ I created a fiddle aswell

like image 745
Elaine Marley Avatar asked Dec 14 '13 15:12

Elaine Marley


People also ask

How do you vertically align an image in a table-cell?

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 you center align vertically in a table?

The vertical-align property sets the vertical alignment (like top, bottom, or middle) of the content in <th> or <td>. By default, the vertical alignment of the content in a table is middle (for both <th> and <td> elements).

How do I center an image in a table-cell CSS?

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.


1 Answers

Put border: 1px solid black on your img, span tags, then inspect both elements in the browser dev. console. You'll notice that the span defaults to 100% height of its parent, while the image has a defined height (the height of the actual image).

So you're not really vertically aligning those elements relative to the div, you're just vertically aligning the text inside the span element relative to the span :)

If you really want to use tables for vertical-centering, here's the correct code: http://jsfiddle.net/WXLsY/

(vertical-align and display:table-cell go on the parent, and you need wrapper table on them)

But there are other ways to do this (SO has many answers to this question, just use search)

like image 141
nice ass Avatar answered Sep 21 '22 17:09

nice ass