Creating responsive Drupal theme (Simplified)

There are various ways to create a responsive Drupal theme, one of them is using template_preprocess_html() function in template.php.

First create template.php if your theme do not already have it. Than add below codes:

* Preprocess html
function themename_preprocess_html(&$vars) {

  drupal_add_css(path_to_theme() . '/css/smartphone.css', array('group' => CSS_THEME, 'media' => 'only screen and (min-width : 240px) and (max-width : 480px)', 'preprocess' => FALSE));

  $meta_viewport = array(
   '#type' => 'html_tag',
   '#tag' => 'meta',
   '#attributes' => array(
     'name' => 'viewport',
     'content' => 'width=device-width, initial-scale=1'

  drupal_add_html_head($meta_viewport, 'viewport');

It is clear if the minimum screen size of 240px and 480px maximum it will use smartphone.css, so please create smartphone.css in css folder and you can add your css code there.

Besides using template.php, you can also add the css via theme's info file like below

stylesheets[screen and (min-width: 240px) and (max-width: 480px)][] = css/smartphone.css
stylesheets[screen and (max-width: 320)][] = css/320.css

And do not forget to add meta viewport via template.php or Android devices will not recognize our responsive layout.

Clear your Drupal cache, once you make above changes.

Redirect non www to www or vice versa (main domain, subdomain)

There is a project that requires me to make the following domain redirection:
  • Redirect all users to access the site WITHOUT the 'www.' prefix for all subdomain.
  • Redirect all users to access the site WITH the 'www.' prefix for main domain only.

To fulfill this purpose, I simply add a few lines of code to the htaccess file:

RewriteEngine on

# Redirect the 'www.' version of the subdomains.
RewriteCond %{HTTP_HOST} ^www\.([^.]+)\.example\.com [NC]
RewriteRule ^(.*)$$1 [R=301,L]

# Redirect the non 'www.' version of the main domain.
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$$1 [L,R=301]

For general use, the following is the code to redirect visitors from non www to www or vice versa.

Redirect all users to access the site WITH the 'www.' prefix:

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Redirect all users to access the site WITHOUT the 'www.' prefix:

RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]