Oct 1, 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

hero_image = find('img[alt=&quot;Hero image&quot;]')
assert hero_image.present?

# Verify the correct mobile image is loaded
assert hero_image['src'].include?('hero-mobile')

end
end

# Generate WebP and AVIF versions
create_webp_version(image)
create_avif_version(image)

# Compress original
optimise_original(image)

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

Have a project idea? Let's talk and bring it to life

Your highly qualified specialists are here. Get in touch to see what we can do together.

Dariusz Michalski

Dariusz Michalski, CEO

dariusz@useo.pl

Konrad Pochodaj

Konrad Pochodaj, CGO

konrad@useo.pl

Have a project idea? Let's talk and bring it to life

Your highly qualified specialists are here. Get in touch to see what we can do together.

Dariusz Michalski

Dariusz Michalski, CEO

dariusz@useo.pl

Konrad Pochodaj

Konrad Pochodaj, CGO

konrad@useo.pl

Have a project idea? Let's talk and bring it to life

Your highly qualified specialists are here. Get in touch to see what we can do together.

Start a Project
our Office

ul. Ofiar Oświęcimskich 17

50-069 Wrocław, Poland

©2009 - 2025 Useo sp. z o.o.

Start a Project
our Office

ul. Ofiar Oświęcimskich 17

50-069 Wrocław, Poland

©2009 - 2025 Useo sp. z o.o.