簡體   English   中英

使用最大高度和最大寬度垂直居中圖像

[英]Vertically centering an image with max-height and max-width

我有以下 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>

使用這些 styles 寬度 > 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;
}

請參閱演示小提琴

好的,我似乎找到了問題所在。 該圖像在提供的鏈接上正確居中,因為它位於 iframe 內。 在正常的頁面流中,圖像將顯示在其封閉容器的頂部。

由於 table et display: table-cell 在 IE 中被破壞,修復需要一個最小的封閉表:

<html>
<head>
<style type="text/css">
#content { border:solid 1px;}   
img{ max-width:400px;max-height:400px;margin:auto;}
#page-table {
    height: 400px;
    width: 400px;
    border-collapse: collapse;
    text-align: center;
    border:solid 1px;
}
#page-td {
    height: 100%;
    padding: 0;
    vertical-align: middle;
}

div#content2{
    border:solid 1px;
    width: 400px;
    height: 400px;
    /*line-height: 400px;*/
    text-align: center;
    display: table-cell;
    vertical-align: middle;
}
img#image2 {
    max-width:400px;
    max-height:400px;
    vertical-align: middle;
}
div#enclosingdiv2 {
    border:solid 1px;
}

</style>
</head>
<body>

With table:
<table id="page-table"><tr><td id="page-td">
<div id="content">
<img src="http://lorempixum.com/250/250/abstract">
</div>
</td></tr></table>

Without:
<div id="content2">
<div id="enclosingdiv2">
<img id="image2" src="http://lorempixum.com/250/250/abstract">
<div>
</div>

</body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM