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.

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

The automatic opening of a modal in a Livewire component is not functioning as expected

I am having trouble displaying a modal when my component initializes. I have tried using $this->emit('show) to open the modal When I add a button in my view, the emit('show') works! However, I want the modal to be automatically shown whe ...

What is the best way to manage the "checked" state of an input checkbox using React?

I'm currently developing an application that features a form with radio buttons. One of the radio button options can be toggled on/off using a checkbox, but I want to ensure that the checkbox is disabled if the corresponding radio button is not selec ...

Conceal a particular row in SharePoint by utilizing JavaScript with jQuery

I'm facing an issue with SharePoint 2010 where the _cts folder is visible in all document libraries. Despite my efforts to research and find a solution, I have been unsuccessful so far. For now, my workaround is to hide the entire row. Here's a ...

Enhancing Website Functionality: How to Swap iFrame for DIV using PHP and AJAX

I am currently working on a website where I need to replace an iframe containing data stored in an invisible form with a div that updates its content using AJAX. If you don't want to read everything, skip to the end for my main question. The chall ...

Retrieve information from every nested array and present it in sequential order

I need to extract the index of each element in a nested array structure. For example, I have an array with 5 subarrays, each containing multiple elements. My goal is to retrieve the first element from each subarray, then the second element, and so on. Her ...

Running two servers at the same time using nodemon might seem complex, but it

Is it possible to run two servers (www.js and apiServer.js) simultaneously using nodemon? I have set the value for the "start" key in package.json as https://i.stack.imgur.com/r8M7p.jpg After running nodemon in the command prompt with the current working ...

Which approach is more impactful: consistently sending an ajax request or breaking down the result within a function?

My JSON data consists of news entries with titles, text, and dates. Here is an example: { "news": [ {"title": "some title #1","text": "text","date": "27.12.15 23:45"}, {"title": "some title #2","text": "text","date": "26.12.15 22:35"}, ... ...

PHP for creating dynamic website search capabilities

As a beginner, I am working on developing an agriculture application to enhance my skills and take on a more advanced project. However, I am facing difficulties in implementing search functionality within the application. Here's what I have: - 4 sele ...

Experiencing difficulty with parsing an array's json/string version within an Angular controller

Updated question for clearer understanding! I'm currently working on an Angular-Rails application and facing challenges when it comes to parsing an array. One of my ActiveRecord models has an attribute that is an array. Before reaching my Angular app ...

How to pass only the clicked element to the onClick function in React.js

I have several elements with the same className, and I want to add the className active to an element (with the className history-node) when it is clicked, in addition to its current className. However, I am facing an issue where the child elements of tha ...

What is the best way to require users to click one of the toggle buttons in a form?

Is it possible to require the user to click one of the toggle buttons in a React form? I want to display an error if the user tries to submit the form without selecting a button. Even though I tried using "required" in the form, it didn't work as expe ...

There seems to be an issue with Jquery not triggering the Webservice method in the Firefox browser, despite it working successfully in Chrome

Currently, I have an issue where a webservice method called via ajax in jQuery is functioning correctly in Chrome and IE browsers but not in Firefox. Here is the jQuery code: $("#btnUpdate").click(function () { var objEmp = { employeeID: $("#Em ...

How can progress bars be animated using CSS or JavaScript?

I am currently working on creating a progress bar animation, but I'm unsure whether to use CSS or JS. Can anyone provide insight on how this effect was achieved here? I am hoping to replicate it. Does anyone know if this is the code they used? I&apos ...

An error has occurred during runtime due to a TypeError: The application is unable to access properties of an undefined object, specifically 'Upload'. This error has

Greetings to the amazing Stack Overflow Community! Currently, I'm developing a Next.js application that requires me to upload videos to Vimeo. To achieve this functionality, I've implemented tus-js-client for handling the uploads. However, I&apo ...

Changing the size of an image in an HTML5 canvas

I have been attempting to generate a thumbnail image on the client side using Javascript and a canvas element. However, when I reduce the size of the image, it appears distorted. It seems as though the resizing is being done with 'Nearest Neighbor&apo ...

Text appearing in varying sizes across browsers

I need some help with a coding issue I'm facing. I have a form where one of the inputs is connected to a JavaScript function that updates a div on the page as the user types. However, I want to limit the width of this div to 900px and make sure it onl ...

Using Javascript, populate an array with Enum variable values

Hey there! I've got this code that creates an array from an enum variable in JavaScript, but it's looking a bit old and clunky. I'm curious if any JavaScript or jQuery experts out there have a cleaner (best practice) approach for achieving ...

CSS: element misplaced at the top instead of the bottom where it belongs

The component with the ID of "#bottom-nav" actually appears at the top. I just designed this on CSS-board, so feel free to review the HTML and CSS code Take a look at it on CSS-desk here It is positioned at the very end of the page and includes a ' ...

I keep encountering an issue with npm where it is unable to identify the executable to run whenever I launch VS Code and attempt to use Cypress

Whenever I open Visual Studio Code and try to run 'npx open cypress', I keep encountering this message in my terminal: npm ERR! could not determine executable to run Oddly enough, running 'npx cypress -v' provides version details, so ...

For Firefox, the status code always comes back as 0 when using xmlhttprequest

When attempting to make asynchronous calls using the xmlhttprequest object, everything functions perfectly in Internet Explorer. However, Firefox seems to be encountering issues. Here is a snippet of the problematic code: if (req.readyState == 4) { i ...