Keep the image proportion (square) the same while allowing the container height to automatically adjust

Encountering an issue while attempting to maintain image aspect ratio

In a container with height: auto; max-width: 640px, I aim to showcase four 1:1 aspect ratio images per row

The dilemma arises when the window's/container's width falls below 640 (small screen device), resulting in elongated images

Is this quandary addressable solely through CSS?

The code snippet is provided below

Thank you in advance

<html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <style type="text/css">
                #container {
                    border: 1px solid red;
                    display: flex;
                    flex-direction: row;
                    flex-wrap: wrap;
                    height: auto;
                    margin: 14px auto;
                    max-width: 640px;
                    width: 100%;
                }

                    #container .child {
                        height: 160px;
                        overflow: hidden;
                        width: 25%; /* 100%/4, only 4 image in each row */
                    }

                        .child img {
                            height: 100%;
                            object-fit: cover;
                            width: 100%;
                        }
            </style>
        </head>
        <body>
            <div id="container">
                <div class="child"> <!-- Image #1 -->
                     <img src="https://s3.amazonaws.com/cdn0.dutchbulbs.com/images/500/60190.jpg">
                </div>
                <div class="child"> <!-- Image #2 -->
                     <img src="https://previews.123rf.com/images/dreamcreation01/dreamcreation011805/dreamcreation01180503640/102424777-it-s-spring-time-banner-with-round-frame-and-flowers-on-blue-sky-background.jpg">
                </div>
                <div class="child"> <!-- Image #3 -->
                     <img src="https://i.pinimg.com/originals/11/2b/74/112b746a2182417b2a947d949798c968.jpg">
                </div>
                <div class="child"> <!-- Image #4 -->
                     <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcT_t3dcCgs9yN7QliI29w0acibdSgVzV9obJw&usqp=CAU">
                </div>
                <div class="child"> <!-- Image #5 -->
                     <img src="https://images-na.ssl-images-amazon.com/images/I/41MrYM42sIL.jpg">
                </div>
                <div class="child"> <!-- Image #6 -->
                     <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSyhn20sg2ZKvx47Gl_1L7sww2W3df_RvjCBA&usqp=CAU">
                </div>
                <div class="child"> <!-- Image #7 -->
                     <img src="https://images.unsplash.com/photo-1464982326199-86f32f81b211?ixlib=rb-1.2.1&w=1000&q=80">
                </div>
                <div class="child"> <!-- Image #8 -->
                     <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcStidi_9IZSp3q2dSqbIOodAd8ib1K3xWMv9g&usqp=CAU">
                </div>
            </div>
        </body>
    </html>

https://i.sstatic.net/owdN5.png

Answer №1

You can use a media query along with max-height to control the image size.

@media (max-width: 640px) {
  #container .child {
    max-height: calc((100vw - 16px) / 4);
  }
}

Keep in mind that the subtraction of 16px is necessary due to the default left/right margin in Chrome and Firefox on the <body> element, which is set at 8px each side. If your margin settings are different, adjust the 16px accordingly to match the total of the left and right margins.

<html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <style type="text/css">
                #container {
                    border: 1px solid red;
                    display: flex;
                    flex-direction: row;
                    flex-wrap: wrap;
                    height: auto;
                    margin: 14px auto;
                    max-width: 640px;
                    width: 100%;
                }

                    #container .child {
                        height: 160px;
                        overflow: hidden;
                        width: 25%; /* 100%/4, displaying 4 images per row */
                    }

                        .child img {
                            height: 100%;
                            object-fit: cover;
                            width: 100%;
                        }
                        
                    @media (max-width: 640px) {
                      #container .child {
                        max-height: calc((100vw - 16px) / 4);
                      }
                    }
            </style>
        </head>
        <body>
            <div id="container">
                <div class="child"> <!-- Displaying Image #1 -->
                     <img src="https://s3.amazonaws.com/cdn0.dutchbulbs.com/images/500/60190.jpg">
                </div>
                <div class="child"> <!-- Displaying Image #2 -->
                     <img src="https://previews.123rf.com/images/dreamcreation01/dreamcreation011805/dreamcreation01180503640/102424777-it-s-spring-time-banner-with-round-frame-and-flowers-on-blue-sky-background.jpg">
                </div>
                <div class="child"> <!-- Displaying Image #3 -->
                     <img src="https://i.pinimg.com/originals/11/2b/74/112b746a2182417b2a947d949798c968.jpg">
                </div>
                <div class="child"> <!-- Displaying Image #4 -->
                     <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcT_t3dcCgs9yN7QliI29w0acibdSgVzV9obJw&usqp=CAU">
                </div>
                <div class="child"> <!-- Displaying Image #5 -->
                     <img src="https://images-na.ssl-images-amazon.com/images/I/41MrYM42sIL.jpg">
                </div>
                <div class="child"> <!-- Displaying Image #6 -->
                     <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSyhn20sg2ZKvx47Gl_1L7sww2W3df_RvjCBA&usqp=CAU">
                </div>
                <div class="child"> <!-- Displaying Image #7 -->
                     <img src="https://images.unsplash.com/photo-1464982326199-86f32f81b211?ixlib=rb-1.2.1&w=1000&q=80">
                </div>
                <div class="child"> <!-- Displaying Image #8 -->
                     <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcStidi_9IZSp3q2dSqbIOodAd8ib1K3xWMv9g&usqp=CAU">
                </div>
            </div>
        </body>
    </html>

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

Embed the CSS from the iframe

** This question is purely hypothetical ** Imagine I have a website with the following code: <head> <style> body { background-color: red; } </style> </head <body> <p>blah</p> </body> If I were to embed th ...

Place the small span element underneath the title span

I am currently working on a layout that includes a list item with the title "Item 0", followed by a small tag containing the text "Description Item 0", and two select menus positioned to the right. The challenge I am facing is placing the small tag below t ...

Is it possible to loop an animation every time the text within the element is altered?

I have an issue with my HTML text element that triggers an animation on page load. I am attempting to write a script that changes the original text to a new one and replays the animation. Here is a snippet of my code: setTimeout(function typewriter() { ...

Refrain from showing content beneath a certain element

Is there a way to hide all content that appears after a specific element, such as a particular class of div? The issue I am facing involves using a 1&1 webpage builder with a restrictive layout-template enforced by my boss. I am trying to remove the foote ...

Matching start and end of CSS selectors using regex

If I have elements with a title attribute like the examples below, how can I select the div with the title custom-marker-wqs-tailrace bbu-l2 using a CSS regex selector? <div title="custom-marker-awlr-tailrace bbu-l2"></div> <div ti ...

Prevent a div from scrolling once it reaches the end of its content, while allowing the other div to continue

I am trying to make the col-md-4 column stop scrolling once it reaches the end of the content, similar to the right sidebar on Facebook. I have attempted using jQuery to add a fixed position when it reaches the bottom, but it is not working as expected. Th ...

Setting Image Height with CSS

I have a div with a height of 105px. The image inside the div is 359px tall. How can I adjust the div's size to prevent cutting off the image and ensure it displays in full height? Thank you for your help! ...

Trouble with closing Bootstrap 4 modal

My Bootstrap 4 modal is causing issues as it pops up on button click but won't close unless I refresh the page. I've been attempting to get it to close by clicking the 'close' button or simply by clicking anywhere on the main page body. ...

Tips for creating child divs with a width that spans the entire page

When viewing multiple rows of containers on my page, the elements shift inline on smaller screens. I am looking to have the orange bar positioned behind and slightly below the header, spanning the width of the page. To achieve this, I utilized relative pos ...

Unable to locate external CSS files in Firefox using the absolute file path

On my website, I have included the following line in the <head> section: <link type="text/css" href="C:/myApps/app1/images/css/12.02/main.css" rel="stylesheet" /> Upon viewing the page in Firefox 11.0, it appears that the main.css file is not ...

What is the process for changing text to red when hovering over it in a nested list?

a { color:black; } a:hover { color:red; } <ol> <a href="#"><li>Main1</li></a> <a href="#"><li>Main2</li> <a href="#"><li>Main3 <ol> ...

Arrange pictures and div elements in a horizontal layout

I am facing an issue with my code that is displaying 5 'cards' in a messed up layout instead of a straight line. I have tried to align them vertically, but some are still higher and not in the right positions. For reference, I want the layout to ...

A guide to accurately accessing form data in Jquery Ajax requests

My beforeSend function is not working properly, as the background color does not change. I suspect it may be due to not correctly referencing the id variable posted from the form. Below is the relevant HTML and JS code: HTML <div id="rec<?php echo ...

Set the clock to the correct time by winding it up

I have created a vintage-inspired clock using javascript and css. function updateClock() { var now = moment(), second = now.seconds() * 6, minute = now.minutes() * 6, hour = now.hours() % 12 / 12 * 360 + 90 + minute / 12; ...

Discovering the hidden: Extracting only the visible portion of text content masked by CSS overflow hidden property

I need a solution for extracting only the text that is visible to the user on a web page, even if there is more content hidden due to CSS styling. Using the standard method driver.find_element_by_css_selector('span#value1').text retrieves the en ...

Redirecting a CSS link on a website

I have a webpage with a "read more" option that redirects to the About Us page. When I click on "read more", the About Us page opens at the top, but I want it to redirect to the bottom of the About Us page. How can I achieve this? ...

Limiting click event to only Image component in Next.js

Is there a way to trigger a click event only on the image itself, rather than the entire parent div? When setting width and height for the parent div, the click event seems to encompass the entire area. For instance, if the image is 600 pixels wide by 300 ...

Breaking the line when combining an image_tag and text in a Rails navbar

Looking for some help combining a logo and brand name in my Bootstrap navbar. I'm running into an issue where there is a line break separating the logo and text. Can someone provide some assistance? <%= link_to image_tag("brand_logo.png") + " Bran ...

Can you provide me with instructions on how to change the background image?

Having trouble with the CSS code I wrote for a background-image. It's not showing up when I set it in my CSS stylesheet. I tested it and found that it only works when written in the body... <body background="Tokyo.png"> ...but not in the styl ...

Acquiring the height of the div

I am trying to achieve a specific layout for my webpage. My goal is to make the background color of the red div match the height of the combined heights of the divs with heights 15.56 + 77.33 + 73.33. <body> <!-- outer div --> <div ...