Loading...
X

How to make images on a site (including WordPress) maintain the correct aspect ratio

How to maintain aspect ratio with HTML IMG tag

An image inserted into a page has the correct proportions by default unless you change it.

When viewing images on a mobile phone, the images are scaled, that is, resized to fit completely on the screen.

Web pages work in a similar way, including sites running WordPress.

But I noticed one issue of displaying large images for which the size is set. On larger screens, these images still display correctly, that is, they retain the correct aspect ratio. But on mobile phones, when the screen width is less than the image width, the image is displayed with distortion, it is stretched vertically, for example:

To fix this problem, add the following rule to the style file:

img{
	object-fit: contain;
}

How to fix wrong image aspect ratio in WordPress

You need to add the specified image style to your WordPress theme's stylesheet. To do this, go to WordPress Dashboard → Appearance → Theme File Editor.

Open the style.css file for editing (it is open by default when you switch to the Theme File Editor).

If you can't use the Theme File Editor, that's not a problem – below is how to edit the style.css file without using the Theme Editor.

Look in the style.css file for the tag:

img {
	……………..
}

In some themes it is already present, in some themes it is not.

If this tag is missing, then add to the style.css file

img {
	object-fit: contain;
}

Another site of mine already has an img tag with the following content:

img {
	max-width: 100%;
	height: auto;
}

In this case, I add a new style to the existing ones, it turned out:

img {
	max-width: 100%;
	height: auto;
	object-fit: contain;
}

After the changes made, images on small screens retain their aspect ratio, even if they do not fit the width of the screen.

Note: If the image is still stretched after making changes to the style file, you need to wait for the site cache to refresh or reset the cache manually. To redownload files from the web server without using the web browser cache, press Ctrl+F5 on the site page. If caching is enabled on your server or at the WordPress level, you need to flush this cache, or wait for it to be updated.

How to edit style.css file without Theme File Editor

If for some reason you cannot use the Theme Editor, then you can edit the style.css file in any other way.

You need access to your site's file system. The specific way to access site files depends on the host and usually webmasters know what to do.

The style.css file is located at the following address:

SITE_FOLDER/wp-content/themes/THEME_NAME/style.css

Leave Your Observation

Your email address will not be published.