ruby on rails
Rails 7.1 adds support for responsive images
•2 min readRails 7.1 has added support for picture_tag. It is useful if we want to add responsive images to our rails app.
Before
Before, If we wanted to add an image to our app, we would use image_tag which supports resolution switching but misses out on art direction, and fallback image.
After
In Rails 7.1, we can use picture_tag for responsive images. picture_tag supports:
- Resolution switching
- Art Direction
- Fallback Image
Usage
Basic
<%= picture_tag("image.webp") %>
Which will generate the following HTML markup:
<picture>
  <img src="image.webp" />
</picture>
Art Direction
<%= picture_tag(
    "image-large.jpg",
    sources: [
      { srcset: "image-square.jpg", media: "(max-width: 600px)" },
      { srcset: "image-rectangle.jpg", media: "(max-width: 1023px)" },
      { srcset: "image-large.jpg", media: "(min-width: 1024px)" }
    ])
%>
Generates:
<picture>
  <source media="(max-width: 600px)" srcset="image-square.jpg">
  <source media="(max-width: 1023px)" srcset="image-rectangle.jpg">
  <source media="(min-width: 1024px)" srcset="image-large.jpg">
  <img src="image-large.jpg">
</picture>
Block
Full control via block:
<%= picture_tag do %>
  <%= tag(:source, srcset: image_path("image.webp")) %>
  <%= tag(:source, srcset: image_path("image.png")) %>
  <%= image_tag("image.png") %>
<% end %>
Generates:
<picture>
  <source srcset="image.webp" />
  <source srcset="image.png" />
  <img src="image.png" />
</picture>
