What is the best way to resize an image within a div that is contained within a grid layout?

I'm currently working with a grid layout. I utilized grid-template-columns and grid-template-rows to outline its structure. My aim is for the first cell to feature an image. To horizontally center it, my plan was to enclose it within a div that can act as a flex or grid container.

I'm encountering difficulties when trying to scale the image. When skipping the div and directly placing the image inside the grid, I can utilize height: 100%; to scale it down so it fits the cell height.

However, adding an extra div container changes things. The use of height: 100% now appears to reference the height of the entire grid layout instead of just the div. According to Google, I should employ max-height and max-width, but I'm struggling to make it function correctly. Below, you'll find a simple test project (both HTML and CSS) illustrating this issue. You can observe how large the sections of the grid should be by using width: 25px;.

I would greatly appreciate any assistance in solving this matter. Remember, this is just a basic test project, so please excuse the naming conventions of my classes and IDs.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body,
html {
  height: 100%;
}

.class {
  background-color: blue;
}

.container {
  height: 100vh;
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 1fr 3fr 3fr;
  gap: 10px;
  background-color: green;
}

#image-container>img {
  max-height: 100%;
}
<div class="container">
  <div class="class" id="image-container">
    <img src="https://www.industrialempathy.com/img/remote/ZiClJf-1920w.jpg" alt="">
  </div>
  <div class="class" id="2">Good</div>
  <div class="class" id="3">Day</div>
</div>

Answer №1

To achieve the desired result, make sure to adjust the overflow on the child element class and set the max-height on the parent element accordingly.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body,
html {
  min-height: 100%;
}

.parent {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 1fr repeat(2, 3fr);
  gap: 1rem;
  background: orchid;
  max-width: 100%;
  max-height: 100vh;
}
.class{
  background: teal;
  overflow: hidden;
}

img{
  display:block;
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class="parent">
  <div class="class">
    <img src="https://www.industrialempathy.com/img/remote/ZiClJf-1920w.jpg" alt="">
  </div>
  <div class="class">
    <p>Good</p>
  </div>
  <div class="class">
    <p>Day</p>
  </div>
</div>

Answer №2

My favorite approach is to set it as the background image, utilizing background-size:contain (or cover) for optimal display. By letting the browser handle the logic, you ensure a fully responsive design without the need to manually adjust.

.exampleA, .exampleB{
    width: 34%;
    height: 150px;
    background-position: center;
    background-repeat: no-repeat;
    background-color: pink;  /* Added for demo purposes */
    border: 1px solid black; /* Added for demo purposes */
    display: inline-block;
}

.exampleA {
    background-size: contain;
}
.exampleB {
    background-size: cover;
}
<div class="exampleA"
     style="background-image: url('https://www.industrialempathy.com/img/remote/ZiClJf-1920w.jpg');"
></div>

<div class="exampleB"
      style="background-image: url('https://www.industrialempathy.com/img/remote/ZiClJf-1920w.jpg');"
></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

Displaying PDF files on the internet without allowing them to be downloaded

How can I display PDF files on my website without allowing them to be saved or downloaded? Is there a way to prevent browsers from saving or downloading the PDF files? ...

What is the best way to showcase a JSON object in an attractive format on a webpage?

Similar Question: JavaScript data formatting/pretty printer var theobject_string = '{...}'; // I have a JSON object as a string. Is there a way to present this string in a visually appealing manner on an HTML webpage? I would like the ...

Difficulties Arising in Flex Layout Usage Due to ngFor Loop Implementation

Despite my efforts, I couldn't locate a question quite similar to mine. If an answer already exists somewhere, I apologize. I'm trying to create a simple flex layout in row format where 2 containers are placed side by side. Inside another compon ...

Perform simple arithmetic operations between a number and a string using Angular within an HTML context

I'm stuck trying to find a straightforward solution to this problem. The array of objects I have contains two values: team.seed: number, team.placement: string In the team.placement, there are simple strings like 7 to indicate 7th place or something ...

Can Javascript be used to identify the number of td elements in a table and specify column widths within the table tags?

Is there a way to automatically add the "col width" tag based on the number of td tags within a Table tag? For example, if there are 2 td's, then it should add 2 "col width", and if there are 3 then, 3 "col width", and so on. <!DOCTYPE html> &l ...

When a div element is clicked, it becomes the selected element and borders are displayed around it

Within a div on my wordpress site, the logo is prominently displayed. Feel free to check it out here: Strange issue - whenever I click on the logo, a large rectangular box suddenly appears. I've experimented with the outline and user-select properti ...

When the source is added with jQuery, the IMG element displays at 0x0 pixels

My latest project involved creating a custom modal popup named #light1. In my JavaScript code, I capture the source from the image the user clicks on and insert it into the img tag with the id of addable. Using jQuery: var images=$('#raam img') ...

Experiencing issues with receiving null values while trying to display variances from a dropdown selection? (Using JavaScript

I am in search of a solution to create a user-friendly nutrition calculator that can analyze the variance between two different food items and display the variations in their nutritional content. However, I'm encountering a couple of hurdles: Althou ...

The Bootstrap modal's submit button refuses to be clicked

I have a unique challenge on my hands - dynamically loading a table within my page where each row is editable in a Bootstrap modal and deletable using multiple checked checkboxes through ajax. Everything works smoothly at first, with the submit button insi ...

Is it possible to automatically pause the background music when the user switches to the next tab?

I am currently working on a website with a HTML5 audio background music player that features an animate effect for fading in and out when playing or pausing. Additionally, I have 2 tabs on the page, one of which contains a YouTube video. I want the backgro ...

Custom Wheel Color Selector plugin enhancement

I am interested in incorporating this plugin into my website https://github.com/fujaru/jquery-wheelcolorpicker/ When we initialize the plugin with the following code: <input type="text" data-wheelcolorpicker="" data-wcp-layout="block"> The default ...

Is it possible to leverage specific client-side Javascript APIs on the server-side?

Exploring APIs designed for web browsers that require their .js code to return audio streams. In a broader sense, these APIs provide byte streams (such as audio) for playback in the browser. Is it possible to use these APIs in server-side Javascript frame ...

What is the proper way to write the code for this form?

I am exploring alternatives to using the html TABLE tag and struggling to create the desired layout. I have attached a screenshot showing my table design. How can I achieve the same layout using divs or spans while still maintaining vertical alignment of t ...

The outcome varies between PHP Local Host and server environments

I have developed a script for searching lk domains. Below is the code: <form action="" method="GET"> <input type="text" name="dm" placeholder="Enter Domain Name"> </form> <?php if (isset($_GET["dm"])) { $domain = $_GET["dm ...

Only one ID is recognized by jQuery

I have a group of three checkboxes set up like this: <input id="image_tagging" class="1" type="checkbox" value="1" checked="checked" name="data[image_tagging]"> Now, I've created an AJAX function (which is functioning correctly), but it seems ...

JavaScript Summation Calculation

I am currently working on calculating the sum of three scores and displaying the total as "Total:". However, I am facing an issue in dynamically updating the total whenever a score value changes. Is there a way to utilize the "onchange" event to achieve th ...

Presentation: Positioning Next Buttons Beside Slide Images While Maintaining Responsiveness

I am facing a challenge with my slideshow project. The slideshow consists of images and text on each slide, along with previous and next buttons that are aligned within the parent container. I am trying to align these buttons at the midpoint of each image ...

How do I trigger a click event on an autocomplete search bar in Vue with a router link enabled?

I'm working on an app that is similar to Github, and I want to create a search bar functionality just like Github's. However, I'm facing an issue with my search bar located in the navbar option section as it doesn't seem to register any ...

Tips for preventing links from moving when hovering and enlarging text in a navigation menu

I'm looking to design a navigation bar for my website that features various links and the company logo. I want the links to have custom spacing, with some aligned on the left and others on the right edge. Additionally, I would like to incorporate a ho ...

A clever CSS hack for showing multiple UL lists with LI elements in different columns, based on the width of the webpage

On my HTML game website, I feature multiple UL lists at the bottom of each page: <h2>How to play?</h2> <ul> <li><a href="/en/ws/google">Via Google</a></li> <li><a href="/en/ws/apple ...