有一些问题显示了如何裁剪和居中图像,但我还没有找到符合这些要求的问题:
- 图像的可见部分必须是正方形
- 应缩放图像,以便显示整个高度并填充容器的高度
- 容器的大小是可变的,由容器的宽度决定
- 图像必须居中
最终目标是拥有一个网格,其中3个正方形图像排成一行,根据浏览器宽度进行收缩。
这是我迄今为止所拥有的。
.i-om-section-content {
max-width: 800px;
border: 3px solid blue;
margin: 0 auto;
padding: 0 32px;
padding: 0 3.2rem;
position: relative;
z-index: 2;
}
.i-om-item {
overflow: hidden;
margin: 10px;
position: relative;
width: 32.5%;
height: 0;
padding-bottom: 32.5%;
border: 1px solid;
float: left;
}
img {
position: absolute;
left: -100%;
right: -100%;
top: 0;
bottom: 0;
margin: auto;
min-height: 100%;
min-width: 100%;
}
<div class="i-om-section-content">
<div class="i-om-item">
<img src="http://onetaste.us/wp-content/uploads/2015/10/DSC2641.png" />
</div>
<div class="i-om-item">
<img src="http://onetaste.us/wp-content/uploads/2015/10/smita.png" />
</div>
</div>
JSFiddle
一般来说,如果您想要对图像进行更多的预先裁剪/定位/调整大小,那么将它们用作背景图像会容易得多。background-size:auto 100%
的意思是"全宽、全高",其余的都是你已经拥有的。
<div class="i-om-section-content">
<div class="i-om-item one">
</div>
<div class="i-om-item two">
</div>
</div>
--
.i-om-section-content {
max-width: 800px;
border: 3px solid blue;
margin: 0 auto;
padding: 0 32px;
padding: 0 3.2rem;
position: relative;
z-index: 2;
}
.i-om-item {
overflow: hidden;
margin: 10px;
position: relative;
width: 32.5%;
height: 0;
padding-bottom: 32.5%;
border: 1px solid;
float: left;
background-size:auto 100%;
background-size:center center;
}
.one{
background-image:url("http://onetaste.us/wp-content/uploads/2015/10/DSC2641.png");
}
.two{
background-image:url("http://onetaste.us/wp-content/uploads/2015/10/smita.png");
}
https://jsfiddle.net/ammsh4y5/
查看此更新的fiddle。
它使用jQuery将容器的高度和宽度设置为相同(使其为方形)。然后,它将图像高度设置为div的高度。最后,它通过获得图像和div的宽度差,将其除以2,并向左移动(绝对定位)来居中图像。
以下是jQuery代码(CSS和HTML也被修改):
function updateImage() {
$("img").each(function() {
var parent = $(this).parent();
parent.height(parent.width());
$(this).height(parent.height());
$(this).css("left", -($(this).width()-parent.width())/2);
});
}
// call on window resize and on load
$(window).resize(function() {
updateImage();
});
updateImage();
这不是最优雅的解决方案,但它能完成任务,而且非常直观。(但我确实喜欢@DylanWatt的background-image
解决方案:更有创意)。
.i-om-section-content {
max-width: 800px;
border: 3px solid blue;
margin: 0 auto;
padding: 0 32px;
padding: 0 3.2rem;
position: relative;
z-index: 2;
}
.i-om-item {
overflow: hidden;
margin: 10px;
position: relative;
width: 32.5%;
height: 0;
padding-bottom: 32.5%;
border: 1px solid;
display:inline-block;
background-position:center center;
}
.one{
background-image:url("http://onetaste.us/wp-content/uploads/2015/10/DSC2641.png");
}
.two{
background-image:url("http://onetaste.us/wp-content/uploads/2015/10/smita.png");
}
<div class="i-om-section-content">
<div class="i-om-item one">
</div>
<div class="i-om-item two">
</div>
</div>