我能夠通過組合@克勞迪奧的table
想法找到自己的解決方案和一些position absolute
魔術。
這裏是解決方案的演示既高又寬的圖像: DEMO
HTML:
<div class="main-box">
<table>
<tr>
<td class="box-title">
<h2>
My title here. :) add some more text
</h2>
</td>
</tr>
<tr>
<td class="box-img">
<img src="//i.imgur.com/NOzWHFF.png" alt="Google">
</td>
</tr>
</table>
</div>
<div class="main-box">
<table>
<tr>
<td class="box-title">
<h2>
My title here. :) add some more text
</h2>
</td>
</tr>
<tr>
<td class="box-img">
<img src="https://upload.wikimedia.org/wikipedia/commons/e/e0/Long_March_2D_launching_VRSS-1.jpg" alt="Google">
</td>
</tr>
</table>
</div>
CSS:
*{
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.main-box{
width: 200px;
height: 200px;
border: 2px solid #000;
background-color: #FFF;
position: relative;
}
.main-box table{
width: 100%;
height: 100%;
border-spacing:0;
}
.main-box .box-title{
background-color: rgba(0, 0, 0, 0.1);
height: 1px;
}
.main-box .box-title h2{
margin: 0;
padding: 5px;
font-family: Helvetica, Arial, sans-serif;
}
.main-box .box-img{
text-align: center;
vertical-align: middle;
padding: 5px;
position: relative;
}
.main-box .box-img img{
max-width: 100%;
max-height: 100%;
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
嗨凱文,也許你已經知道了這個 - 你有問題在這裏解決...圖像將被扭曲/它會溢出'容器',因爲你會[在這裏限制圖像的尺寸](http:// stackover flow.com/questions/39289576/css-image-resize-issue/39289947#39289947))...也很難將圖片居中... – kukkuz
@kukkuz我認爲我沒有問題圖像失真或溢出。我在演示示例中並未限制這兩個維度。我的主要問題是,CSS是否可能知道包含文本的元素的高度,從而導致高度增加。 –