ruby on rails

Rails 7.1 adds support for responsive images

2 min read

Rails 7.1 has added support for picture_tag. It is useful if we want to add responsive images to our rails app.


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.


In Rails 7.1, we can use picture_tag for responsive images. picture_tag supports:

  1. Resolution switching
  2. Art Direction
  3. Fallback Image



<%= picture_tag("image.webp") %>

Which will generate the following HTML markup:

  <img src="image.webp" />

Art Direction

<%= picture_tag(
    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)" }


  <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">


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 %>


  <source srcset="image.webp" />
  <source srcset="image.png" />
  <img src="image.png" />


Written By

Shivam Chahar

Software engineer with almost 4 years of experience in building commercial web apps. Passionate about writing, open-source and building great software.

Get in touch

Comments 💬