cssimageinternet-exploreropera-mini

JS-less responsive images with GIF shown on :hover


Goal: static images with animations shown on :hover that do not exceed container width.

Fixed code:

/* wrapper paragraph*/
.rimg {
	text-align: center;
	overflow: hidden;
}
/* rely on contents for vertical size, show backgrund centered */
.rimg-gif, .rimg-png {
	display: block;
	position: relative;
	background-size: auto 100%;
	background-position: center;
	background-repeat: no-repeat;
	line-height: 0;
}
/* containers need max-width in IE */
.rimg img, .rimg-gif, .rimg-png {
	margin: 0;
	max-width: 99.99999%; /* Opera Mini ignores anything above this % */
	max-width: calc(100% - 0px); /* for proper browsers */
}
/* hide the GIF background unless hovered */
.rimg-gif:not(:hover) {
	background-image: none !important;
}
/* hide the static image when hovered */
.rimg-gif:hover img {
	opacity: 0;
}
<p class="rimg">
  <span class="rimg-png" style="background-image:url(https://i.imgur.com/iwczbln.png)">
    <a class="rimg-gif" target="_blank" href="https://i.imgur.com/TLxp2di.gif" style="background-image:url(https://i.imgur.com/TLxp2di.gif)">
      <img src="https://i.imgur.com/iwczbln.png">
    </a>
  </span>
  Description
</p>

Final structure:

There were a few issues with this:

Additional details:

If anything is unclear, do tell.


Solution

  • After a bit of trial and error I managed to resolve the issues by myself, so I added notes on solutions and the final (working) code to the question.

    I'm not 100% happy with opening a new tab on Android (ideally should play when single-tapping), but all tested browsers close such popup-tabs when pressing Back so maybe it's not too bad. I added a "play" button, which also doubles as a first touch event absorber for mobile (initially covers the link completely, resized to 0% width after a short delay to allow clicking the link). This works both for modern browsers (which trigger :hover and animation playback on first tap and can open link on second tap) and for Opera Mini (which simply opens a popup tab with the GIF). You can see this in action here, for example.