2012-09-01 103 views
1

我試圖限制表內圖像的高度。表格的理由是允許這些圖像垂直和水平對齊到頁面中心。我遇到的問題是,比瀏覽器高度更大的圖像會消失在放大表格的頁面底部,我希望圖像具有max-height:100;和縮放比例。它適用於寬度,但不適用於高度。縮放大中心圖像以適應html表格高度

這裏是我迄今爲止...

<div id="table"> 
<div id="cell"> 
<img src="image.jpg"/> 
</div> 
</div> 

html, body{ 
height:100%; 
margin:0; 
padding:0; 
} 

#table{ 
display:table; 
height:100%; 
width:100%; 
} 

#cell{ 
display:table-cell; 
vertical-align:middle; 
text-align:center; 
background-color:#ccc; 
} 

img{ 
max-width:100%; 
max-height:100%; 
} 
+0

你可以使用一些JavaScript/jQuery? – Chris

+0

演示:http://jsfiddle.net/boyce/mJSxx/ – boyce

+0

@ Abody97 ...我已經設法使用JS插件工作,但也想知道我是否可以純粹用CSS實現。 – boyce

回答

3

你可以做到這一點,而無需使用table。這裏的基本輪廓,HTML:

<body> 
    <img src = "image.jpg"/> 
</body> 

CSS:

html, body { 
    height: 100%; 
    width: 100%; 
} 
body { 
    position: relative; 
} 
img { 
    position: absolute; 
    margin: auto; /*make sure it's centered both vertically and horizontally*/ 
    top: 0; 
    bottom: 0; 
    left: 0; 
    right: 0; 
    max-width: 100%; 
    max-height: 100%; 
} 

而且一點點的jsfiddle演示:little link。請注意,body必須有position: relative;才能正常工作。

我希望這有助於!

+0

@boyce是否適合你? – Chris

+0

是的,這是有效的,謝謝..!現在到我的下一個問題:) – boyce

+0

完美的作品 –

相關問題