Take the 2-minute tour ×

I have a chunk of HTML with has images in it. These image tags have a defined width and height:

<img width="300" height="80" src="image.jpg" />

I would like to go through this HTML and replace the width and heights of the images width a % value instead based off 100%=600 and remove the height attribute all together. So, for example, if an image has a defined width of of 300, the width would be replaced with 50%:

<img width="50%" src="image.jpg" />

I'm pretty rubbish with REGEX, but I image its pretty much going to be the answer. So please help.

In case anyone is wondering, this is needed to format blog post HTML into something that will display friendly on a fluid mobile version of the blog. At the moment, creating actual resized copies of the images is not a viable solution.

I have jquery, jquery mobile available as well if there is a javascript approach to this problem.

share|improve this question
I don't think you need regex for this. Plus if you set width=50% it's relative to the container in which the image is in, not relative to the actual image size. You'd have to use absolute pixel values. –  elclanrs Feb 11 '12 at 19:05
add comment

3 Answers

up vote 0 down vote accepted

Try this simple code:

$('img').removeAttr('height').attr('width', function() {
    return Math.round((this.width * 100)/600) + '%'; 

Or another variant:

$('img').css('width', function() {
}).removeAttr('width height');
share|improve this answer
add comment

Tested, and seems to work:

        var w = $(this).attr('width').match(/\d+/);
        var percent = (w/600)*100;
        $(this).removeAttr('width').css('width',percent + '%');

JS Fiddle demo.

share|improve this answer
add comment

If you don't like to use regexes, you could use DOMDocument to parse your HTML into an object. See here: Regex & PHP - isolate src attribute from img tag

share|improve this answer
add comment

Your Answer


