Tips for using CSS to adjust the width of a parent element based on the width of an image

I'm currently working on developing my own lightbox using React, and I am looking to adjust the width of a div with the class .lightbox-active based on the width of the image it contains. Right now, I have set the parent element to have a max-width: 50%; max-height: 80%, but I want the parent div's width to match the percentage that the image is occupying within the parent element. Is there a way to achieve this without having to calculate the width in JavaScript?

<div className="lightbox-active">
  <img onLoad={() => isFinished()} src={fakeImages[openedImage - 1].url} alt="" />
</div>

The image has the property object-fit: contain which is essential for displaying the image in its original proportions. Without this property, the image fills 50% of the width as its parent but overflows in height.

Here is a link to a working example:

https://codepen.io/freestyle09/pen/rNNdNNg

The green border should match the size of the image:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
.lightbox {
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,.3);
}
.lightbox-active {
  display: flex;
  justify-content: center;
  max-width: 50%;
  max-height: 80%;
  border: 1px solid red;
}

.lightbox-active img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  border: 2px solid green;
}
<div class="lightbox">
  <div class="lightbox-active">
    <img src='https://picsum.photos/1503/1500' alt="" />
  </div>
</div>

Answer №1

If you're looking for a solution, you can utilize the power of position: absolute. This method is highly effective and will cater to your specific requirements.

To implement this, simply adjust the CSS properties of .lightbox-active and .lightbox-active img to incorporate absolute positioning.

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
.lightbox {
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,.3);
}
.lightbox-active {
  max-width: 50%;
  max-height: 80%;
  border: 1px solid red;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}

.lightbox-active img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  border: 2px solid green;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
}
<div class="lightbox">
  <div class="lightbox-active">
    <img src='https://picsum.photos/1503/1500' alt="" />
  </div>
</div>

Answer №2

If you're facing an issue, using inline block and overflow hidden might help partially. However, keep in mind that the bottom of the image may get cropped if it is larger than the available space.

Take a look at the code snippet provided below:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
.lightbox {
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,.3);
}
.lightbox-active {
  display: inline-block;
  overflow:hidden;
  justify-content: center;
  max-width: 50%;
  max-height: 80%;
  border: 1px solid red;
}

.lightbox-active img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  border: 2px solid green;
}
<div class="lightbox">
  <div class="lightbox-active">
    <img src='https://picsum.photos/1503/1500' alt="" />
  </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

Exploring the potential of Django to efficiently implement multiple listviews on a single webpage

Recently started working with Python and Django, but I may have bitten off more than I can chew. If anyone has the time to help educate me, I would greatly appreciate it. My main model deals with "work orders," each of which is linked to subsets of data. I ...

Using a background image in CSS for horizontal rules can override other styling rules

Encountered an unusual CSS bug: After using background-image to style hr, none of the subsequent rules or selectors are displaying on the page: hr { border: 0; height: 1px; background-image: -webkit-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0 ...

Can anyone help me determine the reason why my CSS is being displayed as struck-through in Google Chrome?

After successfully running my app on localhost, I encountered CSS issues when deploying it on Heroku. Some of the CSS appears as struck-through in Chrome. How can I identify what is overriding my styling? https://i.sstatic.net/U23fg.png ...

preventing elements from moving unexpectedly as the navigation bar becomes fixed at the top of the page

I have a website that features a Bootstrap 3 navbar. This navbar is positioned 280px below a block div and becomes sticky at the top of the page when scrolled to that point. HTML (within < head > tags) <script> $(document).ready(function() ...

Instructions for creating a string builder append button that reveals a concealed modal

I'm attempting to add a button using a string builder to append the button in a placeholder. The button will be appended based on a value in the data table. The button append operation is working correctly, but the button's functionality to revea ...

Icons on Google Calendar events - Mini images beside your schedule

I'm in the process of developing a website where I plan to integrate Google Calendar. I want to include a small icon next to specific events to denote certain details. While the "categories" feature in Google Calendar allows me to assign highlight col ...

Transmit HTML message using the "textarea" tag through email

Whenever I try to send the content of my "textarea" via email, it always ends up being sent as a blank message. How can I fix this issue? Below is my PHP code: <?php $input = json_decode(file_get_contents("php://input"), true); $ToEmail = "<a href ...

In JavaScript, I would like to be able to input an end date and have the program calculate and display the number of days remaining until the deadline

I'm working on a school project that involves JavaScript code. I'm struggling with converting a date prompt from string to number format. As a beginner in JavaScript, I could really use some guidance. <script> enddate = prompt('Wh ...

Discover the steps for dynamically integrating ionRangeSliders into your project

Recently, I integrated ionRangeSlider to display values to users using sliders. To set up a slider, we need to define an input tag like this: <input type="text" id="range_26" /> Then, we have to use jQuery to reference the input tag's ID in or ...

Sneaky footer paired with a side panel

Trying to incorporate a sticky footer within the content area of a page that includes a full-height sidebar. Here is a preview of the page I'm currently working on: I have experience using in the past with success, utilizing methods involving percen ...

How can I create a single modal in Ionic 3 that occupies the full screen width and height?

Having trouble resizing my Ionic modal to full screen for just one modal, as Ionic's default settings are overriding any custom changes. I've attempted the following code snippet: @media only screen and (orientation: landscape) { ion-modal { ...

What is the method to display just the final 3 characters within a paragraph?

Is there a way to display only the last three characters of a string using either a method or a string method? I consistently have a 13-digit number, but I specifically require showing only the final three digits. Appreciate any assistance provided. Than ...

CSS hover image resizing not functioning as expected

Is there a way to dynamically scale up an image when hovered over? I'm trying to achieve an effect where the image increases from 100x75 pixels to 300x225 pixels. Everything seems to be working fine with the layout, but the width doesn't seem to ...

I'm in the process of designing a Todo list platform, but I've hit a roadblock trying to figure out the best way to showcase and delete tasks

Having some trouble with creating an li element even after following the necessary steps. Any guidance and explanation would be greatly appreciated. Thank you Managing HTML and CSS is fine, but when it comes to JavaScript, I always seem to struggle. I und ...

Python HTML parser with advanced CSS capabilities

Currently, I am in need of an HTML parser that is aware of CSS and functions similar to how a browser renders HTML. Specifically, I am searching for the equivalent of element.innerText in DOM-JS. For instance, let's consider the following HTML: < ...

Tips for designing a hexagonal chessboard using CSS

I am looking for help with a web development project where I want to create a CSS and HTML version of the hexagonal chess board shown here. My objective is to reproduce the grid structure of the chessboard while excluding the text that accompanies it. Cur ...

What is the method for retrieving context data using useContext in the primary/overall component?

Check out the codesandbox for this code. I have been able to successfully pass and update context data within the child components. However, I am facing an issue where I am unable to access this data in the parent component. Any insights on why this might ...

I'm having trouble inputting text into my applications using React.js and TypeScript

I am encountering an issue where I am unable to enter text in the input fields even though my code seems correct. Can anyone help me figure out what might be causing this problem? Below is the code snippet that I am referring to: const Login: SFC<LoginP ...

How can I stack images on top of each other within a div

Currently, I am in the process of creating a blackjack game and encountering an issue with overlapping cards. Despite implementing the code below, all I see is a column of cards displayed. I have looked at similar questions for guidance, but I'm unab ...

Place a small image within a list item to ensure it matches the height of the list element

I need help aligning images to the right within list elements. The images are squares with equal height and width, and I want them to fit snugly within the height of the list element on the right side. My HTML code is quite simple for now (see example bel ...