01.10.2025
Responsive Images in Rails: Techniques and Tips

Dariusz Michalski
CEO
Learn how to implement responsive images in Rails to enhance website performance, improve user experience, and boost SEO.
@media screen and (min-width: 768px) {
.hero-image {
height: 400px;
background-image: url('hero-desktop.jpg');
}
}
@media screen and (min-width: 768px) {
:root {
--image-width: 450px;
--grid-gap: 2rem;
}
}
.image-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(var(--image-width), 1fr));
gap: var(--grid-gap);
}
@media only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and (min-resolution: 2dppx) {
.logo {
background-image: url('logo@2x.png');
background-size: 200px 100px;
}
}
@media screen and (orientation: portrait) {
.gallery-image {
width: 100%;
margin-bottom: 1rem;
}
}
process :optimize
process quality: 85
end
Clear temporary files
rake tmp:clear
def teardown
current_window.resize_to(*ApplicationSystemTestCase::WINDOW_SIZE)
super
end
end
class ResponsiveImageTest < MobileSystemTestCase
test "hero image loads correctly on mobile" do
visit root_path
end
end
end
end
images_without_alt = page.all('img').select do |img|
img['alt'].nil? || img['alt'].empty?
end
assert_empty images_without_alt, "Found images without alt text: #{images_without_alt.map { |img| img['src'] }}"
end
<!-- Decorative image -->
<%= image_tag "decorative-border.png", alt: "", role: "presentation" %>