2013-02-28 101 views
0

我有一个问题。如何使图像适合div容器?

http://img831.imageshack.us/img831/2111/18435469.png

在这里你可以看到一个形象并不适合容器。 如果宽度,高度固定,但这种布局灵活,并且在调整浏览器窗口大小时图像高度+宽度发生了变化,那么很容易。

也许有一种简单的方法用Javascript来做到这一点?

CSS:

.photo:nth-child(4n+1) { 
background:#ff0000; 
max-width:100%; 
margin: 0; 
clear: both; 
} 

.photo:nth-child(4n+2) { 
background:#EEE; 
max-width: 33.33%; 
min-height: 300px; 
float:left; 
margin: 0; 
} 

.photo:nth-child(4n+3) { 
background:#AAA; 
max-width: 33.33%; 
min-height: 300px; 
float:left; 
margin: 0; 
} 

.photo:nth-child(4n+4) { 
background:#CCC; 
max-width: 33.33%; 
min-height: 300px; 
float:left; 
margin: 0; 
} 
.photo:nth-child(4n+1) img { 
width: 100%; 
} 

.photo:nth-child(4n+2) img { 
max-width: 100%; 
max-height: 100%; 
} 

.photo:nth-child(4n+3) img { 
max-width: 100%; 
max-height: 100%; 
} 

.photo:nth-child(4n+4) img { 
max-width: 100%; 
max-height: 100%; 
} 

PHP代码:

<div class="photo"> 
<img class="group2" href="uploads/'.$row[2].'" src="uploads/'.$row[2].'"/> 
</div> 

回答

0

使用以下的jQuery ....

$(document).ready(function(){ 
var height = $(".photo").height(); 
var width=$(".photo").width(); 
$(".group2").attr("height",height); 
$(".group2").attr("width",width); 
}); 

这将让的高度&宽度,并分配给图片。所以图像适合

注意。 最好总是使用id来获得高度和宽度。

0

这个工作对我来说,只有CSS:

包含分区:

.image_holder { 
overflow:hide; 
} 

图像:

.image_holder img { 
height: 100%; 
max-width: 150%; 
width: auto; 
}