html - 使用 max-height 和 max-width 垂直居中图像

标签 html css

我有以下 html 代码:

<div style="border: 3px coral solid;width:400px;height:400px;background:#D4D0C8;">
    <img style="max-width:400px;max-height:400px;" src="myImage.jpg">
</div>

使用这些样式,宽度大于 400 像素的图像会调整大小但仍保留在 div 的顶部。有没有办法让它们垂直居中?

最佳答案

CSS:

div {
    border: 3px solid coral;
    width: 400px;
    height: 400px;
    background: #d4d0c8;
    line-height: 400px;
    text-align: center;
}
img {
    max-width:400px;
    max-height:400px;
    vertical-align: middle;
}

参见 demo fiddle .

关于html - 使用 max-height 和 max-width 垂直居中图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6635374/

相关文章:

文档准备好后 jQuery width() 立即不正确?

html - Modal 在 IE10 中不工作,但在其他浏览器中工作正常

javascript - 为什么脚本不能识别空 src?

html - 滚动表格内容并修复页面的其余部分

jquery - 如何使用CSS根据图像的宽度响应式地设置按钮的宽度

javascript - 如何使用 cookie 更改 css <link href ="#">?

html - 如何使 div 适合较小屏幕的屏幕边缘?

javascript - 当选中表格中的复选框时,如何换行?

animation - CSS3 动画快退

html - 使用 css 在屏幕上 100% 拉伸(stretch)文本导航元素