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

Position the button at the corner of the textarea

How can I position two buttons below a text_area, aligned with the bottom right corner of the text area? Here is what I have tried so far: Current code snippet: form with modal <%= form_for @note, :url => registrant_notes_path(@registrant), remote: ...

Using <Redirect/> in ReactJS results in rendering of a blank page

Hello everyone, I've been working on a feature where I want to redirect the user to the home page using <Redirect/> from react-router after they have successfully logged in. However, I'm facing an issue where the timeout is functioning corr ...

What steps are necessary to configure .eslintrc to identify the use of 'require'?

I recently started using ESLint and successfully integrated it with IntelliJ. Initially, ESLint did not recognize node out of the box. After consulting the documentation, I created a configuration file named .eslintrc at the project's root folder, sp ...

Using the Loop Function in Node.js with EJS Templates

Seeking help with a node.js application that utilizes bootstrap. I am trying to display the bootstrap cards in rows of 3, with each row containing data from my dataset in columns. However, my current implementation using two for loops is leading to repeate ...

The process of displaying only the month name as the title in Full Calendar

Is there a way to display the Full Calendar title with only the month name instead of "month name year name"? Here is my code attempt: $('#calendar').fullCalendar({ header: { left: 'prev', center: 'title' ...

Adding to and retrieving data from an array

I am relatively new to the world of JavaScript and jQuery, and I have spent the last three days working on a script. Despite my efforts to find a solution by searching online, I have been unsuccessful so far. It seems like my search skills are lacking. My ...

Guide to creating an asynchronous function

Starting my first react website and needing assistance with writing an asynchronous JavaScript function. I am currently working on uploading user input files to firebase storage and then making a post request to the API in order to store the data in the da ...

Customizing number input types in Angular 2 - the perfect solution

Attempting to incorporate a time picker using HTML5 input type number in Angular2. The code snippet below illustrates the setup: <input type="number" [(ngModel)]="hour" (change)="checkHours();" name="one" min="1" max="12"> <input type="number" ...

Submitting a form automatically in React Native using Redux

Is there a way to automatically submit a Redux Form in React Native based on certain conditions being met? I attempted to do so below, but it resulted in a warning. The documentation provides an example for remote submitting, but it uses HTML form's ...

Retrieve data from jQuery and send it to PHP multiple times

<input type="checkbox" value="<?= $servicii_content[$j]['title'] ?>" name="check_list" id="check" /> By using jQuery, I am able to extract multiple values from the table above once the checkboxes are checked. Here's how: var te ...

What causes the lack of upward movement for a div element when the div above it is floated to the left?

Recently, I've been delving into the world of float property in CSS. This is the HTML code snippet I'm working with: .left { float: left; text-align: center; width: 25%; } .normal { text-align: center; width: 25%; } <div class="lef ...

Verify if the value of localStorage matches the specified value, then conceal the element

This is my second query and I'm hoping it covers everything. My knowledge of javascript is limited, which has made it difficult for me to get my code working properly. Despite trying various different approaches, I have been unable to resolve the issu ...

Enhancing user experience with Ajax login forms that seamlessly integrate with browser password remember functionality

I recently implemented an ajax-based login form on my website, but it seems that browsers are not recognizing it as a login form and therefore not offering to remember passwords for easier login access. Once the submit button is clicked, the entered value ...

Customize the appearance of buttons and tabs located in the header section

Front end development is new to me and I'm trying to learn, but I've hit a roadblock. I have 4 components - 2 buttons and 2 tabs that I want to style in a header at the top of the page. Specifically, I want one button on the top left with padding ...

Discovering the special HTML element lacking attributes

When two similar tags, such as anchor tags below, do not have any attributes or css properties associated between them, is there an internal property to distinguish between the two? <html> <body> <a>sample</a> <a>s ...

I have a question regarding the CSS universal selector

I've been working on developing a website, but I'm having trouble with the universal selector. No matter how many times I try, it just won't work. If you'd like to see an example of what I'm dealing with, check out this link: https ...

Unable to retrieve class attributes within a function

I have recently started delving into the world of node.js, and I am facing some challenges with a middleware that I created. The purpose of this middleware is to act as an Error handler. However, I am encountering difficulties in accessing properties that ...

React is struggling to locate the specified module

Once I've set up my react project using npx create-react-app called my-app, I proceed to run npm start only to encounter the error shown in the image below. Running node version: 12.16.1 with npm version: 6.13.4 View the error message her ...

Looking for guidance on implementing throttle with the .hover() function in jQuery?

Seeking a way to efficiently throttle a hover function using jQuery. Despite various examples, none seem to work as intended. The use of $.throttle doesn't throw errors but ends up halting the animation completely. Here is the code snippet in question ...

What is the best way to incorporate an ID from a scala template into an AJAX request?

In my application built on the Play Framework 2.3.8, users can input questions and answers. The view class receives a List[Question] which is iterated through using a for each loop to display them: @for(question <- questionList){ <!-- Questions --& ...