Change image size dynamically using CSS

I am currently working on a photo gallery page where I display images of varying widths and heights. My goal is to use CSS to ensure that all the images are displayed in a uniform width and height dynamically.

While I have successfully managed to set the width dynamically, I am facing challenges with setting the image height. Currently, I manually set the height for the images and adjust them at different breakpoints using @media queries. I don't mind if some excess height is trimmed off (hidden).

@media(max-width: 1300px)
    {
    ul.grid-nav li {
    display: block;
    margin: 0 0 5px;
    }
    ul.grid-nav li a {
    display: block;
    }
    ul.rig {
    margin-left: 0;
    }
    ul.rig li {
    width: 45% !important; /* over-ride all li styles */

    }

    .img { 

    height: 250px; 
    overflow: hidden; 
    }
}

Example Page

Is there any way to dynamically set the height of the .img based on the width of rig.li?

Thank you!

Answer №1

If you want to create a cool effect using relative/absolute positioning and padding, try this trick. Set the padding-bottom as a percentage of the image width.

For images with a 16:9 aspect ratio, apply the following CSS style:

ul.gallery li .img {
    overflow: hidden;
    position: relative;
    padding-bottom: 56.25%;
    height: 0;
}

ul.gallery li img {
    max-width: 100%;
    position: absolute;
}

Answer №2

Check out this jQuery snippet:

$(document).ready(function () { 
    $(".image").css("width", $('ul.gallery li').width());
    $(".image").css("height", $('ul.gallery li').height());
});

I believe this solution may be beneficial to your situation.

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

When using Array() as a constructor in JavaScript, what type of array is generated?

What is the reason Array(42) does not function with an iterator, whereas Array (42).fill() does? ...

Dealing with errors when chaining promises in a react-redux application

This is related to a question asked on Stack Overflow about Handling async errors in a react redux application In my react-redux setup, I am facing a scenario where I need to chain multiple API calls upon successful completion of each. How can I achieve ...

What is a more concise way to write this JavaScript ternary operator?

Exploring an alternative to my ternary logic: mode === 'edition' ? (this.editionMode = true, this.creationMode = false) : (this.creationMode = true, this.editionMode = false) I believe there might be a more efficient way to write this ternary. A ...

Level of importance menu dropdown style

While developing the interface, I encountered z-index complications with the menu and submenu. The main menu should be positioned above, while the submenus should be below. Unfortunately, in the 'Electronics' section, the submenu items are overla ...

Cast your vote with Mysql, Jquery, and Php!

My attempt at creating a voting system using PHP, MySQL, and jQuery seems to be functioning properly on the front-end. However, I am facing an issue where it does not add data to the database on the back-end. Any assistance or suggestions on this matter wo ...

What is the code to programmatically select a checkbox in an ExtJS treepanel when a button is clicked?

I am working with an Extjs treepanel that has several layers added to it. Additionally, I have a search panel with a search button. Clicking on the search button displays the results in an extjs gridview. My goal is to show layers by clicking on a row in ...

Enhance your Rails application with the power of HTML5 validation and JavaScript

In my Rails application, I am facing an issue with the validation form for matching email addresses. Despite showing an error below the form when the email addresses do not match, the form still submits and proceeds to the next page. validations.js if (r ...

The 'string' Type in Typescript cannot be assigned to the specified type

Within the fruit.ts file, I've defined a custom type called Fruit which includes options like "Orange", "Apple", and "Banana" export type Fruit = "Orange" | "Apple" | "Banana" Now, in another TypeScript file, I am importing fruit.ts and trying to as ...

Retrieving the chosen option in Vue.js when the @change event occurs

I have a dropdown menu and I want to perform different actions depending on the selected option. I am using a separate vue.html and TypeScript file. Here is my code snippet: <select name="LeaveType" @change="onChange()" class="f ...

Shipment calculation involves the consideration of factors such as the quantity,

Hello, my name is Mirella and I am from Italy. Please bear with me as I communicate through Google Translate. I am facing some issues with shipping costs while using Simplecart. My customers have varying shipping costs based on the items they purchase. T ...

Canvas featuring labels at the top with a strikethrough effect when utilizing a pie chart in chart.js

I am working on a piece of code that aims to showcase a summary of the most popular forms based on the number of inserted rows in their respective database tables. The goal is to visually represent this data using a pie chart generated with chart.js 2.8. & ...

What is the best approach to display data in React fetched from an API request? If this is not the right method, what changes should be made to the JSX rendering to convert

As I begin my journey with React, I find myself questioning the best practices for displaying data. Should I always break down components into smaller ones rather than having one large component render everything? It seems like a good practice, but I' ...

A guide to building a versatile dropdown component with Material UI or MUI in a React application

Is there a way to create a reusable dropdown component using Material UI or MUI in React? ...

Retrieving data efficiently: utilizing caching in an AngularJS service to store data fetched from a single $http request

Forgive me if this question seems simple or silly, but I find myself in a new scenario and need some guidance. In my AngularJS app, I have a service with 4 methods that share about 80% of the same functionality and code. I want to optimize this and make it ...

JQGrid Dropdown Selection Options

Currently, I am working on developing an MVC application that involves utilizing JQGrid. Within the JQGrid, I have a requirement to display CountryName which is linked to a CountryID. The issue arises when data is retrieved from the database and the Countr ...

Retrieving Information from an Angular 2 Component

Struggling to figure this out, I am attempting to dynamically add user video data that includes a video URL. My goal is to access the data from the component so I can use it in my HTML. I've attempted the following approach. app.component.ts import ...

Error message in Mocha testing: "Function not defined - TypeError: undefined at Test.serverAddress"

Here is a snippet of code from my testing suite: describe('Testing the GET methods', function() { it('Should be able to get the list of articles', function(done) { // SuperTest request request(app).get('/api/articl ...

What happens when Image Buttons are clicked in SAPUI5 and their onchange event is triggered

Is there a way to update the image on a button after it has been clicked? I want it to switch to a different image when activated. var offButton = new sap.ui.commons.Button({ id : "offIcon", icon : "img/off.png" , press :functio ...

Switch between two checkbox options by simply clicking on one without the need for JavaScript

Is there a way to select two combined checkboxes with one click? I have a small calendar where I need to mark weeks using checkboxes. Since one week can fall into two months, I have created duplicates of the same checkbox for each week. Is there a safe wa ...

Examples of panel splitting using Ajax

Looking for recommendations on a tutorial or framework that focuses on creating split panels using Ajax and PHP. The goal is to have two panels, with panel 1 containing a menu that opens content in panel 2 when clicked. Despite numerous searches on Googl ...