I am looking into the methods of styling a Rails app for mobile use.
The idea is common, using one set of styles for mobile browsers and another set for traditional.
From what I can tell there are two basic ways of doing this in Rails:
Using a helper method to detect the user agent and then preform the switch.
application_controller.rb
private
def mobile?
request.user_agent =~ /Mobile|webOS/
end
helper_method :mobile?
application.html.erb
<% unless mobile? %>
<%= stylesheet_link_tag "core" %>
<%else%>
<%= stylesheet_link_tag "mobile" %>
<meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>
<% end%>
Or using media queries in the style sheets
body {
// basic styles
}
@media all and (max-width: 600px) {
body {
// extra styles for mobile
}
}
@media all and (min-width: 600px) {
body {
// extra styles for desktop
}
}
My question is what are the trade offs? Is one method generally better or are there good use cases for both.
Thanks in advance
It depends.
On my personal website I use media queries to change the styles for mobile browsers. This works pretty well in this case because the page has very few images and the majority of style changes are just to make the website vertical and shrink font sizes.
Unfortunately, however, not every mobile phone understands media queries. Further, depending on what you're doing with your media queries, you may be sacrificing performance by using media queries. For example, shrinking the display of big images, or hiding content negatively affects performance in network constrained mobile phones.
For complicated websites, you may also want to render completely different websites to customize the mobile experience. Using the "helper" approach allows you to customize more than just the stylesheet. This also allows mobile users to access the "normal" website on their phone by passing an additional parameter that is taken into account in your mobile?
method.
In summary : If it's simple, media queries are an easy way to customize display, however the mobile experience is likely going to be more holistically different than just minor display tweaks. Trying to use CSS to customize the entire experience isn't a good idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With