我正在创建一个电子商务网站,但我无法垂直居中所有缩略图。问题是我的所有图像都是不同的大小,并使每个图像在所有浏览器中垂直对齐,结果是一种痛苦。我查看了不同的CSS选项,display-table
,line-height
和其他。他们在现代浏览器中工作,但在IE(当然)不太好。我的想法是大型的大型网站正在调整图像大小(我可以毫无问题地做),然后将图像覆盖在背景上方所需的确切大小。有谁知道这是怎么做的?如果是这样,你可以指导我一些如何在PHP中执行此操作的文档吗?
如果有人认为我可以在没有覆盖图像的额外工作的情况下这样做,请告诉我。在这种情况下,你想看看我在这里工作的东西你去了:
HTML
<a href="#">
<div id="product">
<div id="product-image">
<img src="" border="0" />
</div>
<div id="product-name"></div>
<div id="product-price"></div>
</div>
</a>
选项1:JQUERY (这似乎是我最大的希望,但无法让它正常工作)
var h = $('#product-image').height();
$.map($('#product-image img'), function(e)
{
var top =( h- $(e).height())/2;
$(e).css("margin-top",top);
});
选项2:CSS
#product
{
float:left;
margin:5px;
width:200px;
height:200px;
border:1px solid #999;
}
#product-image
{
margin:2px auto;
width:194px;
height:145px;
text-align:center;
}
#product-image img
{
max-height: 100%;
max-width: 100%;
vertical-align:middle;
}
修改
我找到了工作代码,感谢Explosion Pills。对于任何试图完成这项工作的人,我建议使用这个jQuery方法和Fiddle链接http://jsfiddle.net/9VfUS/1/:
工作时间
var h = $('div#product-image').height();
$('div#product-image img').each(function ()
{
var top = (h - $(this).height()) / 2;
$(this).css("margin-top",top);
});
答案 0 :(得分:1)
如果你可以使用JavaScript,我会这样做,因为你可以按照你想要的方式工作。您出于错误的目的使用.map
。你想要.each
:
$('#product-image img').each(function () {
var top = (h - $(this).height()) / 2;
$(this).css("margin-top",top);
});
我认为h
已被正确计算为最高的图像或容器的高度或者你有什么。如果不是,那么你必须这样做。
答案 1 :(得分:0)
如果您事先知道图片的大小,请尝试此操作......
HTML:
<a href="#">
<div class="product">
<div class="product-image" data-image-loc="path_to_your_image"> </div>
<div class="product-name"></div>
<div class="product-price"></div>
</div>
</a>
CSS:
div.product-image {
background-position:center center;
background-repeat:no-repeat;
background-color: transparent;
background-attachment: scroll;
}
div.product-image-width-x-height {
width:{width}px;
height:{height}px;
}
JS:
$(document).ready(function() {
$('div.product-image').each(function() {
$(this).css({backgroundImage:url($(this).attr('data-image-loc'))});
});
});
如果您不知道自己的尺寸,那么将所有图像投放到新尺寸的调整大小脚本可以解决这个问题,您只需将宽度/高度css属性移动到div#product-image CSS声明即可。