To ensure a rectangular image is displayed as a square, adjust its side length to match the width of the parent div dynamically

How can I make the images inside my centered flexbox parent div, #con, be a square with side length equal to the width of the parent div? The image-containing div (.block) is positioned between two text divs (#info and #links). I want the images to be squared even if they contain a different number of images. However, usingbackground-image is not an option in this case. The solution mentioned in this link only works if I specify a specific value for the width (e.g., 300px). This is not an ideal situation as I want it to be dynamic.

var con = $("#con");
$(".block").css("height", con.width(), "width", con.width());

body {
    font-size:1rem;
    text-align:center;
    margin:0;
    height:100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow:hidden;
}

#con {
    width:50%;
    max-width:300px;
    display:flex;
    flex-flow:row wrap;
    justify-content:center;
    margin:5rem auto;
    border:1px solid black;
}

.block {width:100%; overflow:hidden; background:black;}
.block img {
    position: relative;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    object-fit: cover;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<div id="con">
<div id="info">...</div>
<div class="block"><img src="https://dbdzm869oupei.cloudfront.net/img/vinylrugs/preview/60150.png"></div>
<div id="links">...</div>
</div>

Answer №1

To achieve a square aspect ratio, you can utilize the CSS property aspect-ratio: 1 without the need for JavaScript. Additionally, including display: block ensures that the <img> element is not displayed inline by default. The following code snippet demonstrates this concept:

body {
  font-size: 1rem;
  text-align: center;
  margin: 0;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

#con {
  width: 50%;
  max-width: 300px;
  display: flex;
  flex-flow: row wrap;
  justify-content: center;
  margin: 5rem auto;
  border: 1px solid black;
}

.block {
  width: 100%;
  overflow: hidden;
  background: black;
}

.block img {
  display: block;
  object-fit: cover;
  width: 100%;
  aspect-ratio: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<div id="con">
  <div id="info">...</div>
  <div class="block"><img src="https://dbdzm869oupei.cloudfront.net/img/vinylrugs/preview/60150.png"></div>
  <div id="links">...</div>
</div>

In cases where browser support for aspect-ratio is lacking, an alternative method involves using a pseudo-element along with the padding-bottom hack to establish a fixed aspect ratio. This fallback solution is outlined in the following code snippet:

body {
  font-size: 1rem;
  text-align: center;
  margin: 0;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

#con {
  width: 50%;
  max-width: 300px;
  display: flex;
  flex-flow: row wrap;
  justify-content: center;
  margin: 5rem auto;
  border: 1px solid black;
}

.block {
  width: 100%;
  overflow: hidden;
  background: black;
  position: relative;
}

.block::before {
  width: 100%;
  padding-bottom: 100%; 
  content: '';
  display: block; 
}

.block img {
  display: block;
  object-fit: cover;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<div id="con">
  <div id="info">...</div>
  <div class="block"><img src="https://dbdzm869oupei.cloudfront.net/img/vinylrugs/preview/60150.png"></div>
  <div id="links">...</div>
</div>

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 sizing of elements in Firefox seems to be off when using percentage

I am facing an issue with a page that has 3 td elements all set at a width of 33.333333%. In Firefox, the browser seems to be computing it as an actual pixel value of 568px, causing the containers to run off the page. I have not defined any fixed widths in ...

Requesting Access-Control-Request-Headers using jQuery Ajax POST method

I am attempting to send an AJAX request to my server. Initially, I referenced a library (in the web) within a <script> tag in my HTML document and executed it using the following code: $.ajax({ url: api_url + "movie/create", type : "POST", con ...

Froala Editor: Innovative external toolbar that pops up when the button is clicked

In our project, we are implementing the latest version of Froala and aim to configure it so that the toolbar is activated by a separate external button, similar to Gmail where the editor initially does not display a toolbar. I attempted to modify the &apo ...

What could be causing the target to malfunction in this situation?

Initially, I create an index page with frames named after popular websites such as NASA, Google, YouTube, etc. Then, on the search page, <input id="main_category_lan1" value="test" /> <a href="javascript:void(0)" onmouseover=" window.open ...

Replacing default hover behavior from an external library

Currently, I am utilizing a JS library that comes with a specific widget. Basically, I have the following list (I removed unnecessary DOM code): <li class="disabled"> When I hover over this list item, it turns into: <li class="disabled state-a ...

Unable to assign unique identifiers to elements within a user interface framework

I am having difficulty assigning an id to components. Scenario 1: - Trying to assign an id to an HTML component. <h1 id="demo-h1">Demo Heading</h1> Assigning id to HTML component Scenario 2: - Attempting to assign an id to a componen ...

Tips for sending the output of a Python function to the webpage associated with the clicked action button in Python's Bottle framework

Here is a method I have: @post('/home', method='post') def myFunction(): if(len(request.forms.get('Matrix_dimension').strip()) != 0): length = int(request.forms.get('Matrix_dimension').strip()) tableRow = ...

Arranging Divs next to each other, ensuring uniform column heights, within a ContentPlaceHolder in ASP.NET

I am attempting to create a layout with three columns. The left and right columns will each contain a button that should remain aligned with the outer border of the container. In the center column, there will be an asp:Table generated dynamically, ranging ...

A beginner's guide to crafting a knex query with MySQL language

Within MySQL Workbench, I currently have the following code: USE my_db; SELECT transactions.created_at, price FROM transactions JOIN transactions_items ON transactions.id = transactions_items.transaction_id JOIN store_items ...

Utilizing CSS to dynamically update the nth-child selector

I've created an image gallery with a 2-column layout, allowing for full-width images to be interspersed between the columns. To see an example of this, check out my Codepen: <div class="gallery"> <img src="http://nosrc.io/200x200"> ...

Open a separate window by clicking on an image using JQuery

I've been trying to figure out how to open an image in a new tab when the user clicks on the thumbnail, but none of the solutions I've attempted seem to be working for me. Here is the jQuery code I have tried: $('#imagelink').click(fu ...

Exploring the Art of Programming SVG

I am thinking about creating a website that is similar to stackoverflow, but with the added feature of allowing answers to include drawings such as schematics. I would like to have a section in the answer form where users can create these schematics with ...

When building websites, pages, or applications with React, how do you determine the best choice between JavaScript, TypeScript, or JavaScriptXML?

After completing my portfolio and an eCommerce website design using Figma, I started learning React and Tailwind with Vite. I'm comfortable with basic JavaScript but now I want to understand the differences between .js, .jsx, and .ts files when workin ...

Issue encountered when trying to use Array.sort() method to sort an array of objects

I'm facing an issue sorting an array of objects by a name property present on each object. When utilizing the sort() method with the given code snippet, I encounter the following error: ERROR ReferenceError: b is not defined This is my code block: m ...

I am uncertain about whether it would be better to utilize URL path parameters or query parameters for filtering on the back-end of the application

Suppose I am trying to retrieve all car models from a specific brand. This can be achieved by utilizing URL path parameters or query parameters as shown below: router.get('/modelsByBrand', modelController.getModelsByBrand); To make the GET reque ...

"Revolutionizing the way we navigate: Angular's innovative

Presently, my focus is on incorporating route transitions into my project. I've employed a component that appears on click and triggers the corresponding service function: routeTransition(destination) { if (this.router.url !== destination) { t ...

"Encountering an issue with supabase.auth.getUser() when implementing a vue-router route guard

My Vue application project involves integrating Supabase authentication. In one of the route guards within the router file, I used supabase.auth.getUser() to determine the user's login status and control the execution flow based on that condition: // ...

What is the best way to send data into functions?

I'm trying to avoid using global variables and I'm facing some difficulties in figuring out how to pass the database variable into the addTrain function. Do I necessarily need to use global variables for the database? $(document).ready(function( ...

Reading inputs from a Text Area using ko.JS databinding - Issue with capturing new lines

This is the code I have written for a text area: <div> <textarea data-bind="value: environment" rows="10" cols="20" class="form-group"></textarea> </div> I am looking to show the content typed in this text area in another DIV. ...

Is there a way to convert the items in the products variable into the more comprehensive detailedProducts?

New to JS, looking for guidance on transforming the products variable into detailedProducts in JavaScript const products = [ { title: 'Yellow Pail', submitterAvatarUrl: 'images/avatars/daniel.jpg', productImageUrl: 'images ...