问题
I'm new working with listviews in jQuery mobile.
The CSS code i'm using to override the default used with jQuery mobile is:
<style type="text/css">
.has-odd-thumb li a {
padding-left: 90px !important;
padding-top: 0px;
padding-bottom: 0px;
}
.thumbContainer {
position: absolute;
left: 0; top: 0; bottom: 0;
width: 80px;
height: 80px;
overflow: hidden;
}
.thumbContainer img {
display: block;
margin: auto;
max-height: 80px;
}
</style>
This is to make my non-squared images fit correctly when they are thumbnails in the different items in my list.
This is the code to my list (simplified for quick reference):
<ul id="lista" data-role="listview" data-filter="true" data-filter-reveal="true" data-filter-placeholder="Search..." data-inset="true" class="has-odd-thumb">
<li><a href="#" id="1" class="item-lista">
<div class="thumbContainer">
<img src="img/test.jpg">
</div>
<h2><i>Item</i></h2>
<p>Description text</p>
</a></li></ul>
Until now everything works fine, I have the images fitted inside the 80px square thumbnail, but my problem is if the image is wider (a rectangle) it doesn't appear centered in the square space of the thumbnail. It appear aligned to the left. How can I make the image centered in that square space?
Thanks
EDITED:
回答1:
Example
.thumbContainer {
position: absolute;
left: 0; top: 0; bottom: 0;
width: 80px;
height: 80px;
overflow: hidden;
}
.thumbContainer img {
position: relative;
left: -50%;
margin-left: 50%;
display: block;
margin: auto;
max-height: 80px;
}
This answer does not cover with portrait rectangles... which is why I'd recommend the background image or Javascript methods.
回答2:
Demo
As promised here is some simple JQuery to cover your thumbnail with the correct ratios & center them.
$(document).ready(function () {
// Find thumbnail containers
$('.thumbContainer').each(function () {
// Get current thumbnail container
var thumb = $(this);
// Get current thumbnail image
var img = thumb.children('img');
// Calculate image ratio
var ratio = img.innerWidth() / img.innerHeight();
var newW, newH;
// Calculate new width & height
if (ratio >= 1) {
newH = thumb.innerHeight();
newW = newH * ratio;
} else {
newW = thumb.innerWidth();
newH = newW / ratio;
}
// Apply new width & height
img.width(newW);
img.height(newH);
// Calculate and apply offsets
// You can replace thumb.outerHeight / width with exact values if you want
img.css('top', (thumb.outerHeight() - newH) / 2);
img.css('left', (thumb.outerWidth() - newW) / 2);
});
});
回答3:
You could set the images as background images and use:
background-size: cover;
http://www.w3schools.com/cssref/css3_pr_background-size.asp
...or calculate the exact scale with some Javascript.
来源:https://stackoverflow.com/questions/23795147/horizontal-align-the-thumbnail-in-a-jquery-mobile-listview