Can you use display: table-cell and have a fixed width/height?

CodeWombat picture CodeWombat · Aug 8, 2011 · Viewed 45.5k times · Source

I have the following:

CSS:

.photo {
  overflow: hidden;
  display: table-cell;
  vertical-align: middle;
  text-align: center;
  width: 100px;
  height: 100px;
}

HAML

.photo
  %img{:src => my_url}

See the jsFiddle here. The image I used to demonstrate is 150px by 80px.

I need to display the image inside the .photo div and crop off any excess. The image needs to be centered vertically and horizontally. However, display:table-cell causes the .photo div to ignore my width and height settings. How can I get around this?

Answer

MatTheCat picture MatTheCat · Aug 8, 2011

table-cell is not the only solution to vertical-align.

.photo {
    overflow: hidden;
    background: #c0c0c0;
    display:inline-block; /* or float:left; */
    text-align: center;
    width: 100px;
    height: 100px;
    line-height:97px;
}
.photo img {
    vertical-align:middle;
    max-width:100%;
    max-height:100%;
}