Automatically add width and height to img tags

14 Jul 2024

If you set the width and height attributes for your img tags, the browser can allocate the correct amount of space for the image before loading it. This prevents content below the image from shifting around as the page loads. The layout becomes stable, which means that:

That’s why Google recommends setting the width and height attributes in your HTML code.

If you have a lot of images, it may take some time to specify their dimensions. With Aba Search and Replace, you can do it automatically.

The typical case

Adding width and height to HTML images

Please use this search pattern to capture the image file name in the first subexpression:

<img src="([^"]+)"

The [^"]+ regex matches everything except for the closing quotation mark and parentheses mark the first subexpression.

If you have absolute paths like <img src="/images/someImage.png"> in your HTML code, use the following replacement:

\0 \{ File(Aba.searchPath() \1).meta('ImgTag') }

Here, we insert the whole match \0, which is the img tag and its src attribute. Then, we insert width and height via the meta function. The Aba.searchPath() function returns the directory that you selected for the search, then the image filename \1 is added to it.

Relative paths

Adding width and height to HTML images with relative paths

If your paths are relative to the html files (e.g., <img src="someImage.png"> or <img src="../banner.png">), then use a simpler replacement:

\0 \{ File(\1).meta('ImgTag') }

Replacing existing width and height attributes

If you have existing width and height attributes and you want to replace them, the regex becomes more complex. For example, if the width and height always follow the src attribute:

<img src="([^"]+)" width="\d+" height="\d+"

And the replacement should be:

<img src="\1" \{File(Aba.searchPath() \1).meta('ImgTag')}
Matching the existing width and height attributes

Conclusion

You can preview the replacements and check that the img tags are matched correctly. If Aba cannot find an image file, it will display an error message with the src attribute and the HTML filename. Then, just press the Replace button and test the result in your browser. If anything goes wrong, you can always undo the replacement.

Aba can help you to ensure that all of your pages use width and height attributes, which improves performance, prevents layout shifts, and makes your website more visually appealing for the users.

Aba Search and Replace screenshot

Replacing text in several files used to be a tedious and error-prone task. Aba Search and Replace solves the problem, allowing you to correct errors on your web pages, replace banners and copyright notices, change method names, and perform other text-processing tasks.

This is a blog about Aba Search and Replace, a tool for replacing text in multiple files.