Become Wordpress Professional - Your Ultimate Wordpress Guide

Wednesday, 3 April 2013

How to Make Wordpress Images Responsive

Responsive images in wordpress
Responsive designs are the ones that adjust themselves according to the width and height of the device they are being viewed from, for example an image being viewed on a PC will be shown according to the width and height of the computer screen or an image viewed on an iPad or iPhone will have its dimensions adjusted according to the screen environment.  This makes responsive designs more flexible and a better option to go for.

Creating Responsive Images in Wordpress

Responsive images in wordpress can be added by using small bits of codes. First of we need to create a simple shortcode and place it in functions.php file. Below is the code to create a shortcode that will be helpful in making images responsive:
// Creating a shortcode function
function adding_responsive_images( $atts, $content = null ){

// Returning a div with class responsive-image, this class will later be styled in theme's style.css to make it responsive
return '
' . $content . '
'; } //The following code generates the shortcode: add_shortcode( 'responsive', 'adding_responsive_images' );
Now that we have added the shortcode to our theme's function.php file, lets style this div which will actually make it responsive. Open up your theme's style.css and add the following code to it:
@media only screen and (max-width:767px) {
    .image-resized img {
        width:100%;
        height:auto;
    }
}
Basically the above code says that if the screen's max width is 767px ( that is for the iPad ) then resize it accordingly.

Next all you need to do is to add the short code inside a post or a page wherever you would like your image to be.
[responsive]ALT Text [/responsive]
Just remember to place a correct URL to image otherwise you might face broken image issue.
Now that you know of a useful way to make wordpress images responsive, move on and give it a try!

2 comments:

  1. Thank you. A couple of corrections for you though.
    1. after creating the function for the responsive div you need to create the shortcode.
    add_shortcode( 'responsive', 'adding_responsive_images' );
    2. the correct class for the css is .responsive-image not .image-resized

    Otherwise everything worked great.

    ReplyDelete
    Replies
    1. Thank you for the corrections Edward :)

      Delete

Please Avoid Spamming. Comments will be moderated before they are published.