Remove IMG height and width with jQuery

WordPress automatically adds inline width and height when you insert images into your Pages or Posts. This can cause layout problems, especially in IE, if you use CSS to change the dimensions of your images. For instance, max-width: 100px; height: auto; will not work in some browsers, because they resepect the inline height over the CSS.

The sollutions is simple: Remove the width and height attributes with jQuery. The following code between <head> and </head> will do the job:

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function($){

	$('img').each(function(){ 
		$(this).removeAttr('width')
		$(this).removeAttr('height');
	});

});
</script>

Note that this code will remove width and height on all images. You can use class or ID selectors if you just want to remove it on some, say in the sidebar: $('#sidebar img').each(function(){

11 thoughts on “Remove IMG height and width with jQuery

  1. Nancy Johnson

    Hi,

    I think this is a great idea. I couldn’t get it to work in IE8 however, worked in IE 7 and all other browsers…

    I tried removing your jquery core, because I have a plugin that uses a jquery core. This too worked in all browsers except IE8

    There may have been a conflict with this plugin…

    http://wordpress.org/extend/plugins/wordpress-tabs-slides/installation/
    After I added the jquery to the header below wphead, the tabbed plugin sometimes didn’t display in IE8.. however when I moved your jquery/javascript to display before WPhead in header.php, it fixed this issue, however it still didn’t work and the images were distorted.

    I much prefer to control the widths of images in the CSS and I generally do not use the height element.

    Thanks

    Nancy Johnson

    Reply
    1. Kevin

      As of jquery version 1.7, it can be even a space-separated list of attributes. So:

      $(‘img’).removeAttr(‘width height’);

      does the job perfectly.

      Reply
  2. SnH

    Good workaround..can you please explain if it’s possible to find particular image src and do it for that one alone?

    Regards

    Reply
  3. Lavern

    I was wondering if you ever thought of changing the page layout of your site?

    Its very well written; I love what youve got to say.
    But maybe you could a little more in the way of content so people could connect with it better.

    Youve got an awful lot of text for only having 1 or 2 images.
    Maybe you could space it out better?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *