Guide on creating uniform heights and widths for images with varying dimensions utilizing CSS (and percentage values)

Is there a way to ensure that all images maintain the same height and width using CSS percentages, rather than set pixel values? I'm working on displaying images in circles, where most are uniform in size but a few outliers distort the shape. The wide images fit properly, but the tall ones appear oval-shaped.

https://i.sstatic.net/GZry6.png

I'm not concerned about adjusting the wide images as they already fit within the circle. However, the issue lies with the taller images that need to be corrected.

A snippet of the HTML (JavaScript -- Google Maps API InfoWindow)

for (i = 0; i < myList[infoId].numOfFUnits; i++) {
    infoString = infoString + ("<a href=\"" + myList[infoId].fUnits[i].pageLink + "\"><img src=\"" +
        myList[infoId].f[i].photo + "\" class=\"mPhoto\" alt=\"" + myList[infoId].fUnits[i].displayName + "\"></a>");
}
infoString = infoString + ("<br/><strong>Images</strong></div>");

var infoBox = new google.maps.InfoWindow({
    content: infoString,
});

CSS

.mPhoto{
    margin-top: 5px;
    width: 30%;
    height: auto;
    border-radius: 50%;
    border: 1px solid white;
}
  • One solution I've tried is setting max-height to 188.09px (equal to full screen width), but this causes issues when the window is resized smaller.
  • Since the HTML is within JavaScript, I can't use
    document.getElementsByClassName().style
    to adjust the max-height based on current width.
  • Attempts to use background images require specific pixel dimensions instead of percentages.
  • Changing object-fit didn't have the desired effect, despite initial appearances.

Do you have any suggestions?

Answer №1

To prevent tall images from appearing as ovals, make sure to specify a max-height for the images.

Answer №2

If you want responsive perfect circles, the width must match the height when the screen size changes.

To accomplish this, JavaScript can be used to adjust the values accordingly as the page resizes.

Check out this example below:

var width = $(window).width();
var height = $(window).height();

$(window).resize(function() {
  // Set the height and width variables on resize
  width = $(window).width();
  height = $(window).height();
  
  console.log(width);
  console.log(height);

  // Collect the images
  var images = document.getElementsByClassName('img');
  
  // Adjust width based on window size
  if (width > $(window).width()) {
    for (var i = 0; i < images.length; i++) {
      images[i].style.width++;
    }
  }
  
  // Decrease width if necessary
  if (width < $(window).width()) {
    for (var i = 0; i < images.length; i++) {
      images[i].style.width--;
    }
  }

  // Increase height when needed
  if (height > $(window).height()) {
    for (var i = 0; i < images.length; i++) {
      images[i].style.height++;
    }
  }
  
  // Reduce height if necessary
  if (height < $(window).height()) {
    for (var i = 0; i < images.length; i++) {
      images[i].style.height--;
    }
  }
});
.img {
  position: relative;
  float: left;
  background-position: 50% 50%;
  background-repeat: no-repeat;
  background-size: cover;
  border-radius: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="img" style="background-image:url('http://i.imgur.com/tI5jq2c.jpg'); width: 100px; height: 100px;"></div>
<div class="img" style="background-image:url('http://i.imgur.com/37w80TG.jpg'); width: 100px; height: 100px;"></div>
<div class="img" style="background-image:url('http://i.imgur.com/B1MCOtx.jpg'); width: 100px; height: 100px;"></div>

This example uses inline styles to set the initial width and height because it's easier to update them dynamically with JavaScript rather than if they were in a stylesheet.

Although there may be more efficient ways to achieve this effect, this solution should work for your needs :)

You can test this out by running the code snippet and viewing it in full-page mode. Resize the page to see the circular images adjusting while maintaining their shape.

I hope this explanation helps!

Answer №3

Have you considered using object-fit: cover:

.photo {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

Keep in mind that when using object-fit, you need to explicitly declare the values for both width and height for it to function properly. These values can also be specified using relative units.

Answer №4

The challenge I encountered was the need to set the width and height based on a percentage of something other than the image size itself. Initially, setting both dimensions to 30% resulted in them being relative to the image's original size which was not helpful. On the other hand, using fixed values like 200px provided a solution but lacked responsiveness.

As noted by Gerardo BLANCO before their comment was deleted, utilizing viewport height (vh) or viewport width (vw) as units proved to be effective (1 vh represents 1% of the viewport height, while 1 vw equals 1% of the viewport width). A more versatile alternative is employing vmin, equivalent to 1% of the smaller dimension between width and height of the viewport.

(Please keep in mind that vmin may encounter compatibility issues with older browsers and exhibit glitches in Edge.)

.mPhoto{
    margin-top: 5px;
    width: 30vmin;
    height: 30vmin;
    border-radius: 50%;
    border: 1px solid white;
}

This approach not only ensured uniform image sizes but also allowed for dynamic adjustment of circle sizes when resizing the browser, eliminating the need to constantly refresh the InfoWindow.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for accessing a local .json file from a remote machine or folder?

I am currently working on a project that involves a .json file stored in my local folder. Along with the file, I have Javascript code in the same directory to access and read the values from the .json file. To open the file, this is the line of code I use: ...

Image overlaying the full width of body content background

I am trying to find a solution to my problem, but so far no luck. The Body selector has a max-width of 85%, and there are other selectors like header which I want to have a background image that spans 100% of the width behind the body selector attribute. ...

Fade between two elements using jQuery

Can someone assist me with adding a fade effect between elements in my code? Any advice or suggestions would be greatly appreciated! $("#example p:first").css("display", "block"); jQuery.fn.timer = function() { if(!$(this).children("p:last-child").i ...

Utilizing Three.js to apply a matrix transformation to a collection of objects and subsequently refreshing their positions

How can we ensure that objects added to a group in a scene (now Object3D()) correctly apply the group's matrix, updating their locations within the scene? ...

The failover process for PayPal involves seamless transitions to backup systems in the

I am currently assisting a client with a unique architecture setup: Back End Running on Java Server Front End Powered by Proxy (Node JS + Express application) For security reasons, all requests made to the server must pass through the Proxy. We ar ...

Pattern matching for directory path excluding the filename

Looking for assistance with creating a JavaScript regex pattern to validate text input as folder paths only, excluding the filename. Can someone provide guidance on this? For example: folder1/folder2/folder3 => valid folder1/folder2/filename.txt1 =&g ...

How to link a sandbox file in HTML with an iPhone

Looking to create an HTML application specifically for the iPad, I am interested in developing a background process using Objective-C that will handle the downloading of images and data. The goal is to be able to access these resources from within an HTML ...

Eliminate borders surrounding WordPress text widgets

Looking for some help with removing the border around the widgets on my home page. Despite my theme's CSS removing borders universally, I thought targeting specific Div text widgets (such as text-7, text-6) would do the trick. While I can control the ...

CSS transitions/transforms are failing to impact the necessary elements

I'm currently grappling with advanced transitions and transforms, and encountering some challenges with a section I'm developing. I've managed to get everything working as needed, except for the fact that there is an h5 element positioned ov ...

NodeJS: Extract images based on specified coordinates

Dealing with images that contain text can be a challenge, but by using tesseract and the imagemagick node module, I was able to extract the text successfully. The only issue I encountered was related to the image size. https://i.sstatic.net/XldZC.png For ...

What is the method for customizing the background color in a .vue file using Bootstrap?

Can anyone assist me in updating the background color of a div class from grey to white? The code is within a .vue file using Bootstrap and includes an enclosed SVG file. Here's the snippet: <div class="text-left my-3 bg-white"> <button var ...

Using Async functions with Node.js Express.js router

I've been trying to search on Google, but I can't seem to find a clear answer to this one... Is it possible to pass ES7 async functions to the Express router? For example: var express = require('express'); var app = express(); app.ge ...

Dynamic reloading of a div with form data using jQuery's AJAX functionality

I am currently developing an online visitor chat software using PHP and MySQL. My goal is to load the page when the submit button is clicked. Submit Button ID: send Visitor ID: vid Chat ID: cid Below is the snippet of code for an Ajax request that I hav ...

Using custom or external fonts icons in Chrome Packaged Apps involves the following steps:

Seeking to enhance the appearance of my Chrome Packaged App built in AngularDart, I searched for external icons online but came up empty-handed. Despite attempting various strategies and implementing the workaround provided below, I have been unable to ach ...

Is it possible to enable a button as soon as input is entered?

I'm encountering a minor issue with my button's functionality. I am attempting to have the button enabled as soon as text input is entered into the text field, but currently it only becomes enabled after the focus has changed from the text field. ...

Inserting line breaks in the data retrieved through AJAX

Utilizing ajax to transfer data from a sophisticated custom field wysiwyg editor. Within the markup provided, I am specifically addressing the div with the 'bio' class. However, upon receiving the data, it is consolidated into one large paragraph ...

Multer can handle the uploading of various files from multiple inputs within a single form

I've searched everywhere on the internet, but I can't seem to find a solution that matches my specific issue. As someone new to Node.JS, I'm attempting to upload two different pictures using Multer from the same form. Here's what my for ...

Incorporating HTML and JavaScript into TypeScript: How to Embed a Shopify Buy Button in a .tsx document

I am currently looking to integrate Shopify with my personal website. My frontend is built using React (NextJS with TypeScript). The embed code for the Shopify buy button consists of an HTML div tag wrapping JavaScript. I am wondering how I can effectivel ...

Adding nested JSON data to MySQL using NodeJS

My current challenge involves using Node.js to INSERT JSON data into a MySQL database. Everything runs smoothly until I encounter nested values within the JSON structure. Here is an example snippet of my JSON data: var result2 = [{ "id": 89304, "employe ...

Listening to changes in a URL using JQuery

Is there a way to detect when the browser URL has been modified? I am facing the following situation: On my webpage, I have an iframe that changes its content and updates the browser's URL through JavaScript when a user interacts with it. However, no ...