CSS: positioning and resizing image while maintaining aspect ratio

Is there a way to center and resize an image in html/css while maintaining its aspect ratio?

I currently have a solution that centers the image, but it does not scale up when necessary. Here is the code snippet: http://jsfiddle.net/4Mvan/438/

.container {
    margin: 10px;
    width: 115px;
    height: 115px;
    line-height: 115px;
    text-align: center;
    border: 1px solid red;
}

.resize_fit_center {
    max-width:100%;
    max-height:100%;
    vertical-align: middle;
}

I am looking for a solution that works across all major browsers, including IE10+

Thank you!

Answer №1

Eliminate the inner img element and try this method instead.

This approach is effective regardless of the image proportions.

.container {
    margin: 10px;
    width: 115px;
    height: 115px;
    border: 1px solid red;
    background: url(http://i.imgur.com/H9lpVkZ.jpg) no-repeat center center;
    background-size: contain;    
}
<div class='container'>
</div>

<div class='container' style='width:50px;height:100px;line-height:100px'>
</div>

<div class='container' style='width:140px;height:70px;line-height:70px'>
</div>

This particular one will expand proportionally
<div class='container' style='width:350px;height:350px;line-height:350px'>
</div>

If you are aware of the specific image properties for each container, you can maintain your html structure and utilize this technique.

.container {
    margin: 10px;
    width: 115px;
    height: 115px;
    line-height: 115px;
    text-align: center;
    border: 1px solid red;
}
.resize_fit_center {
    vertical-align: middle;
}
.fit_width {
    width:100%;
}
.fit_height {
    height:100%;
}
<div class='container'>
    <img class='resize_fit_center fit_width'
      src='http://i.imgur.com/H9lpVkZ.jpg' />
</div>

<div class='container' style='width:50px;height:100px;line-height:100px'>
    <img class='resize_fit_center fit_width'
      src='http://i.imgur.com/H9lpVkZ.jpg' />
</div>

<div class='container' style='width:140px;height:70px;line-height:70px'>
    <img class='resize_fit_center fit_height'
      src='http://i.imgur.com/H9lpVkZ.jpg' />
</div>

This specific one will enlarge accordingly
<div class='container' style='width:350px;height:350px;line-height:350px'>
    <img class='resize_fit_center fit_width'
      src='http://i.imgur.com/H9lpVkZ.jpg' />
</div>

Answer №2

If you have pre-knowledge of the image's aspect ratio, you can employ media queries along with aspect-ratio to achieve desired results.

In my scenario, I am aware that my image holds a 4:3 aspect ratio.

Utilizing media queries allows me to switch between filling the height when it's the constraint (aspect ratio wider than 4/3) and filling the width when it's the limiting factor.

img {
  height: 100%;
  width: auto;
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
}

@media screen and (max-aspect-ratio: 4/3) {
  img {
    height: auto;
    width: 100%;
  }
}

https://jsfiddle.net/0cjc23oz/

Answer №3

To transform your .resize_fit_center, simply insert width:100%; height:auto; like this:

.resize_fit_center {
    width:100%;
    height:auto;
    max-width:100%;
    max-height:100%;
    vertical-align: middle;
}

Answer №4

Instead of fixed width for elements, consider using relative units like percentages and setting max-width to 100%. This approach should help resolve the issue.

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

Adjusting webpage zoom based on different screen sizes

Hey there, I ran into an issue with my web page design. It looks great on my desktop monitors, but when I checked it on my laptop, things went haywire. Strangely, adjusting the zoom to 67% seemed to fix the problem. Both screens have a resolution of 1920 ...

"Troubleshooting Bootstrap nav-pills' failure to update displayed content

I'm currently working on creating a dynamic navbar that updates the content based on which navigation pill is selected. For some reason, the content in my div.tab-content isn't changing as expected... Here is an example of the code I am using: ...

Error encountered when trying to load Ajax script

As a beginner in the learning process, my code may appear messy. I am currently wrapping up my second project, which is a photo viewer. On the main page, there is a navigation system that loads different sections of the website using ajax. Since this proje ...

Incorporate Bootstrap into your Bigcommerce stencil theme for seamless design integration

As a newcomer to BigCommerce's Stencil theme, I am looking for guidance on integrating Bootstrap into the theme for local development. Is it feasible to incorporate custom CSS and JS into the Stencil theme as well? ...

Converting a Powershell array into an HTML format

I have three arrays that I need to display on an HTML page: foreach($item in $array1){ // write array data to HTML } foreach($element in $array2){ // write array data to HTML } foreach($value in $array3){ // write array data to HTML } What is the ...

How can I combine HTML and CSS in a single request using the sendFile method in Express?

const app = require('express')(); app.get('/', function(req, res) { res.sendFile(__dirname + "/" + "index.html"); }); <link rel="stylesheet" href="style.css"> I utilized the Node.js code above to send an HTML file. In order to ...

Guide to centering Embed horizontally with Bootstrap 5

My goal is to create a centralized input with an image positioned above it. I have been following the guidelines provided in the position documentation, but the image still does not align horizontally: https://i.sstatic.net/awWxL.png Here's the code ...

When using jQuery, the PHP variable value is not retrieved from the DIV data-id attribute, instead it just displays the variable name

I currently have the following code: <div class= "obutton feature2" data-id=".$bookID."><button>Reserve Book</button></div> <div class="modal-box"></div> Although this button triggers the jQuery script, the modal box ...

Increasing box width in Django

I'm currently working on a website using Django all-auth for authentication. Everything is functioning perfectly, but I'm wondering if there's a way to increase the size of the username and password input boxes using HTML. Below is the code ...

XPaths are used to verify the accuracy and relevance of text content

Here's a snippet of HTML I need help with: HTML Code: <a id="pINumber" href="csf.ajax?et=p.preparationinsurance">PASS170XX</a> XPATH to identify the above element //*[@id="pINumber"] I am looking to create an XPATH that checks for the ...

Calculate the total amount from the selected items on the list, depending on the clicked ('active') element

My main objective is to achieve the following: Before any clicks || After the user selects the desired item After conducting some research, I successfully implemented this using vue.js https://jsfiddle.net/Hanstopz/Lcnxtg51/10/ However, I encountered ...

One effective way to redirect after a PUT request and display a one-time message

Here's what I'm aiming for in terms of desired behaviour: A user navigates to a password change web page. The user completes the form and it is sent via PUT request to our REST server. Upon successful completion, the user is redirected to their ...

``There seems to be an issue with the functionality of the href link

Currently, I am utilizing purecss to design colorful buttons on my website. However, I am encountering an issue where the href link is not clickable even though the button displays correctly. <button class='pure-u-1 pure-button pure-button-primary ...

Arrangement of SVGs within one another

I am working on achieving a layout with multiple SVG elements arranged in a specific way. This layout involves a top-level gray box containing several orange boxes, each of which holds red boxes. The width and height of the top-level SVG are known. https: ...

Using jQuery or Javascript to enclose every character in a given string with an HTML tag

I am trying to create a function that can take a string of text and wrap each letter within that string with an HTML tag such as <i> or <span>. Although I have made some progress, the current solution is not working as expected. The issue I a ...

What causes my animation to “reset” upon adding a new element using innerHTML?

One of the functionalities on my webpage involves a script that inserts a div called "doge" using innerHTML when a button is clicked. Additionally, there is a CSS keyframes animation applied to another div on the same page. However, whenever the button is ...

How can we add up the sum with just one click and then display the

Is there a way to calculate numbers within specific DIV boxes and display the total in a separate DIV when a box is clicked? I've attempted different methods, including enclosing the code within the window.onclick function. Check out my code on this J ...

The process for incorporating two distinct Google fonts into a Next.js project using Material UI

Currently in the process of upgrading my MUI5 application from Next 12 to Next 13 and experimenting with integrating next/font. In my previous Next 12 version, I utilized two Google fonts - 'Rubik' and 'Ephesis' which were included in t ...

Struggling with certain CSS design elements

I'm encountering some CSS styling issues. The button in my form remains perfectly positioned when I resize the window, but the inputs are moving around. Why is this happening? Also, when a button is pushed, a h2 element with a little arrow needs to b ...

Padding for the doughnut chart in Chart.js canvas

My current setup includes a canvas featuring a doughnut chart created with chart.js enclosed in a div element that displays like this: https://i.sstatic.net/yy1e4.png The canvas has a red background to enhance visibility. Currently, the chart is centered ...