JSFiddle link

HTML:

<div id="va-m">
    <img src="http://placehold.it/150x150">
    <h1> vertical-align: middle </h1>
</div>
<div id="no-va">
    <img src="http://placehold.it/150x150">
    <h1> no vertical align </h1>
</div>

CSS:

div {
    margin-top: 30px;
    padding: 5px;

    width: 500px;
    height: 150px;
    line-height: 200px;
    background-color: blue;
}

#va-m img {
    vertical-align: middle;
}

h1 {
    display: inline;
}

img {
    border-radius: 75px;
}

I'm trying to align the image and text vertically in the container div. However, I seem to either get the choice of aligning the image, or aligning the text. Using vertical-align: middle on the img tag pushes it out of the container. Why?

有帮助吗?

解决方案

Change the height to auto

Fiddle

div {
    margin-top: 30px;
    padding: 5px;    
    width: 500px;
    //height: 150px;
    height: auto;
    line-height: 200px;
    background-color: blue;
}

Update: Use table and table-cell + vertical-align: middle

Fiddle

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top