Anjanesh Lekshminarayanan




Different attribute values for an HTML element based on responsiveness

This is really a server-side solution and not using CSS's media queries

Anjanesh Lekshminarayanan's photo
Anjanesh Lekshminarayanan
·Sep 6, 2022·

1 min read

There was a situation where I need to set the width and height attributes of an image without the CSS, since I was setting the CSS height via TailWindCSS's classnames based on responsiveness - h-9 sm:h-20 - h-9 for mobile view and h-20 for desktop view. Because Setting Height And Width On Images Is Important Again for Google's PageSpeed Insights, I had to set the width and height attributes of the HTML img element on the server side, using PHP.

detectmobilebrowsers has real short insert-able snippets for almost every web language. For PHP, its at

You'll get a 3 line code like below - the regular expression is not included in this post as it's too long.

Include this in your base php file :

if(preg_match('/this is a very long regular expression/i',substr($useragent,0,4)))
    $GLOBALS['isMobile'] = true;

Then, in the HTML file you can set the width and height attributes :

$dimensions = 'width="80" height="80"';
if (isset($GLOBALS['isMobile']) && $GLOBALS['isMobile'])
    $dimensions = 'width="36" height="36"';

Now my img tag in my HTML looks like this :

<img class="h-9 sm:h-20" src="" alt="my image" <?php echo $dimensions ?> />

Now Google PageSpeed Insights won't complain of images without dimensions.

Share this