How to add viewport and other responsive meta tags to drupal

Responsive design is the need of every website. Without a responsive design you lag behind in the ever growing technology and standards. Responsive design is the key to deliver a perfect website to all devices that come in different sizes ranging from 3 inches to 21 inches.

How to add viewport and other responsive meta tags to drupal


While designing with drupal it is common to add a responsive design code to the website as drupal does not have one. Let's get to add then.

The Process

For doing this you need access to the theme folder.
Open the theme folder situated at /sites/all/themes/YOURTHEME
Open this file template.php and write this code

The Code

function theme_page_alter($page) {  
$mobileoptimized = array(  
     '#type' => 'html_tag',  
     '#tag' => 'meta',  
     '#attributes' => array(  
     'name' => 'MobileOptimized',  
     'content' => 'width'  
     )  
);  
$handheldfriendly = array(  
    '#type' => 'html_tag',  
    '#tag' => 'meta',  
    '#attributes' => array(  
    'name' => 'HandheldFriendly',  
    'content' => 'true'  
    )  
);  
$viewport = array(  
    '#type' => 'html_tag',  
    '#tag' => 'meta',  
    '#attributes' => array(  
    'name' => 'viewport',  
    'content' => 'width=device-width, initial-scale=1'  
    )  
);  
drupal_add_html_head($mobileoptimized, 'MobileOptimized');  
drupal_add_html_head($handheldfriendly, 'HandheldFriendly');  
drupal_add_html_head($viewport, 'viewport');  
}  

The Logic

The theme_page_alter() alters each and every page.
The drupal_add_html_head() adds the meta tags in the <head> of the html output file.
So this adds the three tags as shown below
<meta name="MobileOptimized" content="width">
<meta name="HandheldFriendly" content="true">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

This will now support the @media queries in the CSS. That means you can start styling.

Liked it, Share it

Give Your Response

customizing comment box

Prism