Adjust the size of an image to fit within a set height row using CSS grid

I have a container with fixed width and height where I want to display an image and some text. My goal is to have the text appear first, followed by the image filling up the remaining space in the container. Check out the image below for reference:

Example Image

Although it seems like this approach should work, the image doesn't respect the height of the row it's placed in:

.container {
  width: 500px;
  height: 300px;
  background-color: green;
  display: grid;
  grid-template-rows: 1fr auto;
  gap: 40px;
}

img {
  object-fit: contain;
  width: 100%;
  background-color: red;
}

span {
  background-color: blue;
}

<a href='somelink' class="container">
  <img src="https://cdn.pixabay.com/photo/2017/02/07/16/47/kingfisher-2046453_960_720.jpg" alt="">
  <span>Test</span>
</a>

Answer №1

After some trial and error, I finally cracked the code! It seems that enclosing the image in a div AND adding overflow:hidden does the trick. This ensures that the image is properly resized instead of just stretching to fit its container.

body {
  display: flex;
  flex-direction: column;
  align-items: stretch;
  min-height: 100vh;
  margin: 0;
}

.container {
  width: 500px;
  height: 300px;
  background-color: green;
  display: grid;
  grid-template-rows: 1fr auto;
  gap: 40px;
}

.image-container {
  overflow: hidden;
  display: flex;
  justify-content: center;
  background-color: red;
}

img {
  display: flex;
  flex: 0 1 auto;
  object-fit: contain;
  background-color: red;
}

span {
  background-color: blue;
  color: white;
}
<a href='somelink' class="container">
  <div class="image-container">
    <img src="https://cdn.pixabay.com/photo/2017/02/07/16/47/kingfisher-2046453_960_720.jpg" alt="">
  </div>
  <span>Test</span>
</a>

Answer №2

When setting the height of your text to 40px, be careful with long texts as they may overflow the container. To manage the part of the picture you want to see, consider using the object-position property along with object-fit: cover;

.container {
  width: 500px;
  height: 300px; 
  background-color: green;
  display: grid;
  grid-template-rows: 1fr auto;
  gap: 40px;
}

img {
  object-fit: contain;
  width: 100%;
  height: 100%;
  background-color: red;
}

span {
  background-color: blue;
}
<a href='somelink' class="container">
   <img src="https://cdn.pixabay.com/photo/2017/02/07/16/47/kingfisher-2046453_960_720.jpg" alt="">
   <span>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque pretium lectus id turpis. Nulla est. Maecenas sollicitudin. Nullam justo enim, consectetuer nec, ullamcorper ac, vestibulum in, elit. Pellentesque pretium lectus id turpis. Nullam faucibus mi quis velit. Nullam justo enim, consecte...
   </span>
</a>

.container {
  width: 500px;
  height: 300px;
  display: grid;
  grid-template-rows: 1fr auto;
  background-color: limegreen;
  gap: 20px;
}

img {
  width: 100%;
  height: 100%;
  background-color: red;
  object-fit: cover;
  object-position: right top;
}

span {
  background-color: blue;
  color: white;
  text-align: center;
}
<div class="container">
  <img src="https://cdn.pixabay.com/photo/2017/02/07/16/47/kingfisher-2046453_960_720.jpg" alt="">
  <span>Some text Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque pretium lectus id turpis. Nulla est. Maecenas sollicitudin. Nullam justo enim, consectetuer nec, ullamcorper ac, vestibulum in, elit. Pellentesque pretium lectus id turpis. Nullam faucibus mi quis...
</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

Changing the shape of a background using CSS when hovering

My Bootstrap navigation has a unique setup, as shown below. I've observed that many users tend to only interact with the headings and ignore the submenus where the actual products are located. To address this issue, I want to change the design of th ...

When utilizing the "as" attribute, styled components do not inherit any styles

I am currently utilizing both styled-system and styled components, working on a simple scenario like the one below: const buttonFont = { fontFamily: "Chilanka" }; // define basic text styling const Text = styled.div` ${typography} ${color} `; // c ...

Is it possible to simultaneously center and display an iframe inline?

I have a YouTube video that I'm trying to center within a div. After adding display: block; to the CSS following advice from How to center an iframe horizontally?, it centers correctly, but now I want to display two images inline next to the iframe ...

Add at the beginning of each row in the text area

I have a small text area on my webpage where I want to add ">>" to the beginning of each line. My initial attempt was to use this code: $("#mytextarea").prepend("EvilHacker001>>"); Unfortunately, this did not produce the desired result. I searched ...

Error: The function window.intlTelInput is not recognized within the ReactJS framework

I am currently learning ReactJS and encountering an issue when using jQuery with React JS for intlTelInput. I have installed npm jQuery and imported all the necessary code. Additionally, I have included all the required CSS and jQuery links in my index.htm ...

AgGrid's magical dropdown feature

Struggling to integrate a bootstrap-4 dropdown menu with AgGrid, I'm facing an issue where the data table overlaps the dropdown when the html is present. Attempts to increase the z-index have not yielded results. Below is the html code snippet: < ...

There seems to be an issue with the CSS header alignment as the logo is not properly positioned using a top margin of -20px

My goal is to create a header bar that includes an image, a title, and a menu car. I want the bar to be displayed after scrolling 50px down, and I also want the image to be positioned slightly above the wrapping div, showing a bit of it in the top 50px. Ri ...

html interactive/expandable tree

I've come across this code which generates an HTML tree, but I'm facing an issue where the tree expands every time I refresh the page. What I want to achieve is to have certain branches expanded and others collapsed when the page is opened, depe ...

What is the best way to adjust the spacing between posts on a website

https://i.stack.imgur.com/VderY.jpg Looking at the image, there are 3 posts lined up in a row. I'm trying to adjust the spacing between each item to be about 20%. Specifically, I want the distance highlighted by the red dashes, instead of the current ...

What is the best way to manage DOM modifications in a responsive design layout?

Developing a responsive website with only one breakpoint can be challenging, especially when restructuring the DOM to accommodate different screen sizes. It's important to consider not just CSS and media queries, but also how the elements are arranged ...

I'm struggling to make my div display inline

My div elements are not displaying inline, I'm thinking maybe I shouldn't use the nav and div structure like this. But starting over again seems like a lot of work. How can I fix this issue? Just so you know, I'm only on my 4th day of learn ...

How can we seamlessly transition from adding a class to setting scrollTop on a particular div?

I have successfully implemented a jQuery script to change the background color of my navbar on scroll. Here's the code I used: jQuery(document).ready(function($) { $(window).scroll(function() { var scrollPos = $(window).scrollTop(), nav ...

Maintaining the image's aspect ratio while cropping it to fit within the maximum or minimum height

Is there a way to make an image responsive by resizing it while keeping its aspect ratio intact at all sizes? I want the height of the image to stay fixed above 650px, cropping the top and bottom to maintain the ratio without stretching. Additionally, I do ...

Tips on implementing CSS to the subpar class in Vuejs

I am working on an HTML file that operates with button in Vue.js. The v-bind:class can be utilized for a single tag as shown below. It disappears based on the boolean value of bool data. <h3 v-bind:class="{active: bool}">{{counter.document}}&l ...

Vue.js - Problem with loading image on screen

Although I have experience with React, I am currently facing the challenge of using Vue for a code assessment for the first time. My struggle lies in creating a reusable image component with WAI-ARIA accessibility. Despite my efforts, I cannot get the imag ...

Troublesome situation arising from CSS floats overlapping div elements

It's strange how this issue always occurs when using floats. This is what my div (samle) looks like: <div class="main> <div class="inn_div">&nbsp</div> </div> Here is my stylesheet: .main{ width:250px; border:1px ...

What is the solution for getting `overflow-x` to function in place of `overflow-y`?

I have a main container with several sub-containers inside. When the main container's width exceeds its limit, I want to display a horizontal scroll bar. Instead of using the 'display: inline-block' property because it creates unwanted whit ...

Is it possible to customize the background color of select2 boxes separately for each option?

I recently implemented the select2 plugin and now I'm looking to add a new class within the .select2-results .select2-highlighted class in order to change the background color. Does anyone have any suggestions on how to achieve this? ...

Tips for setting a Bootstrap 3 dropdown menu to automatically open when located within a collapsed navbar

Is there a way to have my dropdown menu automatically open when the collapsed navbar is opened? Take a look at this example I created in a fiddle to see what I'm working with so far. Right now, when you click on the navbar in its collapsed state, two ...