开发者

Vertical-align a variable-size image in a div?

Edit: A note to anyone reading this, the whole reason it didn't work for me is because I was using DOCTYPE TRANSITIONAL. Which no change in HTML or CSS whatsoever, switching to DOCTYPE STRICT made it work. This is true for at least Chrome, FF, and IE8.

I have tried many many solutions offered online and none of them seem to work for me. I am trying to vertical-align an image inside a div (the image is already horizontal-aligned).

The image can be any width and any height (up to 70px) so I can't use a fixed margin or anything like that.

Here is my HTML+CSS:

<head>
    <style type="text/css" media="all">
    #list ul {
        list-style: none;
        margin: 0px;
        padding: 0px;
    }
    #list li {
        border: 2px solid #DDD;
        margin-bottom: 3px;
        height: 110px;
    }
    #image {
        width: 75px;
        height: 110px;
        line-height: 110px;
        float: left;
    }
    #image img {
        vertical-align: middle;
        display: block;
        margin: auto;
    }
    #event {
        margin-left: 75px;
    }
    </style>
</head>

<body>
<div id='container'>
    <div id="list">
        <ul>
            <li>
                <div id='image'>
                    <img src='http://sstatic.net/stackov开发者_StackOverflow中文版erflow/img/favicon.ico'/>
                </div>
                <div id='event'>
                    <h1>Text</h1>
                    <h2>More Text</h2>
                </div>
            </li>
            <li>
                <div id='image'>
                    <img src='http://sstatic.net/stackoverflow/img/favicon.ico'/>
                </div>
                <div id='event'>
                    <h1>Text</h1>
                    <h2>More Text</h2>
                </div>
            </li>
        </ul>
    </div>
</div>
</body>
</html>


You can't use vertical-align on a block element. An image is usually an inline element, but you have yours explicitly set to display: block. Remove that, and set the line-height of the parent div to the div's height.

Works here: http://jsfiddle.net/YnzR9/1/

#image {
    width: 75px;
    height: 100%;
    float: left;
    line-height: 110px;
    text-align: center;
}
#image img {
    vertical-align: middle;
}


Set the "line-height" of the div to the same value as the height of the div.

Update: Assuming you want the image vertically aligned and centered, use the following.

#image {
    width: 75px;
    height: 110px;
    float: left;
    line-height: 110px;
    text-align:center;
}
#image img {
    vertical-align: middle;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜