Вопрос

I need to vertically center an image, I don't know it's dimensions ahead of time so the only option I really have is using tables or css tables I believe.

I thought I'd give css tables a go but I still can't get an image to vertically center in them.

My HTML:

<div class="image">
    <div class="table">
        <div class="table_row">
            <div class="table_cell">
                <img src="https://pbs.twimg.com/profile_images/3560817062/a9bda79c4d2bfc3353a4fbc0a14e6080.jpeg" alt="Main Image">
            </div>
        </div>
    </div>
</div>

CSS:

.table {
    display: table;
    margin: 0px auto;
}

.table_row {
    display: table-row;
}

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

.image {
    width: 411px;
    min-width: 411px;
    max-width: 411px;
    height: 341px;
    min-height: 341px;
    max-height: 341px;
    background-color: #f6f6f6;
}

.image img {

}

Fiddle: http://jsfiddle.net/5DLuU/

What am I doing wrong here?

Это было полезно?

Решение

First at all you don't need the <div> for table-row you can work only with the table-cell, to solve the align issue assign the height:100% for the table and table-cell:

.table {
    height:100%;
    display: table;
    margin: 0px auto;
}
.table_cell {
    height:100%;
    display: table-cell;
    vertical-align: middle;
}

Check this Demo Fiddle

Другие советы

You can use line-height and vertical-center like:

HTML:

<div class="image">
    <img src="https://pbs.twimg.com/profile_images/3560817062/a9bda79c4d2bfc3353a4fbc0a14e6080.jpeg" alt="Main Image"/>
</div>

CSS:

.image
{
    background-color: #f6f6f6;
    width:400px;
    height:400px;
    line-height:400px;
    text-align:center;
}

.image img
{
    vertical-align:middle;
}

The problem is, your table does not have enough height to cover the outer div. You can give a specific height to it.

.table {
    display: table;
    margin: 0px auto;
    height:350px;

}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top