Odd-sized Thumbnails in Listview


jQuery Mobile (jQM) provides a listview widget that works well in most scenarios to provide a nice looking vertical list familiar to users of mobile devices.  If you include an image in the list item markup, jQM will automatically format it as an 80px by 80px thumbnail on the left side. If the provided image is smaller than 80×80 it sits at the top left corner; and if it is larger than 80×80 and not square it will also sit at the top left corner and either fill the width or the height but not both.

So if you have a list with oddly sized thumbnails having different width to height ratios, you end up with a list that looks unaligned:

With a little CSS and an extra DOM element we can center the thumbnails both horizontally and vertically within the 80×80 square on the left.

The standard listview markup looks like this:

<ul data-role="listview" data-inset="true">
  <li>
    <a href="#">
      <img src="image.jpg">
      <h2>Item Text</h2>
      <p>Item Description</p>
    </a>
  </li>
</ul>

For our solution, we will apply a class to the UL element (has-odd-thumb) to distinguish it from other UL elements on the page that do not have this issue and surround the IMAGE with an absolutely positioned DIV. The DIV is assigned a class of thumbContainer:

<ul data-role="listview" data-inset="true" class="has-odd-thumb">
  <li>
    <a href="#">
      <div class="thumbContainer">
        <img src="http://lorempixel.com/600/300/food/4" />
      </div>
       <h2>Food</h2>
       <p>600 x 300 sized icon</p>
    </a>
  </li>
</ul>

In CSS, we first provide padding of 90px on the left of the A tag so the text will not overlap our image.  Next, we position the thumbContainer DIV absolutely on the left of the list item and give it a width of 80px. Finally, we position the IMAGE absolutely within its square container. Setting margin: auto centers the image within the container, while setting the max-width and max-height to 80px ensures that larger images will be scaled down to fit.

.has-odd-thumb li a {
    padding-left: 80px !important;
}
.thumbContainer {
    position: absolute;
    left: 0; top: 0; bottom: 0;
    width: 80px;
}
.thumbContainer img {
    position: absolute;
    margin: auto;
    bottom: 0; left: 0; top: 0; right: 0;
    max-width: 80px;
    max-height: 80px;
}

Here is our newly aligned listview:

This trick works equally well in jQM 1.3 and 1.4 with no changes to the markup or CSS.

Buy Me A Coffee :) @ ko-fi.com

Advertisements

Drop me a line or two ;)

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s