Enclose an image with a <div> element while maintaining the <div> height at

Encountering a challenge where positioning an element on top of an image at specific coordinates (20% from the top and 30% from the left) is required.

Initially, the solution involved wrapping the image in a div with a relative position and using absolute positioning for the element. However, this approach failed to work consistently across different browsers.

Upon loading the provided fiddle, the dummy image displays correctly initially. Yet, when adjusting the size of the window in Chrome or Firefox, the red div containing the image becomes visible, causing the element to shift from its intended position. Interestingly, this issue does not occur in Safari.

The main question now is: How can the image be kept tightly wrapped at all times?

UPDATE: It is essential that the div containing the image remains 100% the size of its parent without deviation.

Fiddle: http://jsfiddle.net/12q26xu7/2/

html,
body {
  height: 90%;
  padding: 0;
  margin: 0;
  text-align: center;
}
.child-wrapper {
  height: 50%;
}
.image-wrap {
  position: relative;
  height: 100%;
  display: inline-block;
  background: red;
  border: 1px solid blue;
}
.image-wrap img {
  max-height: 100%;
  max-width: 100%;
  width: auto;
  height: auto;
  vertical-align: middle;
}
.image-wrap .point {
  position: absolute;
  left: 20%;
  top: 30%;
  border-radius: 50%;
  background: #000000;
  width: 10px;
  height: 10px;
}
<html>

<body>
  <div class="child-wrapper">
    <div class="image-wrap">
      <img class="viewer__image" src="http://dummyimage.com/300">
      <div class="point"></div>
    </div>
  </div>
</body>

</html>

Answer №1

To set the height and width of your div as automatic, use the following CSS code:

.image-wrap {
    position:relative;
    height: auto;
    width:auto;
    display: inline-block;
    background: green;
    border: 1px solid black;
}

Check out the updated fiddle here

UPDATE

In response to your revised query regarding maintaining 100% height with aspect ratio width, achieving this might require JavaScript. The following script should help accomplish this:

$('.image-wrap').each(function () {
    var wrap = $(this),
        image = wrap.children('img:eq(0)'),
        ratio = image.width() / image.height();

    wrap.data('ratio', ratio);
});

$(window).resize(function () {
    $('.image-wrap').each(function () {
        var wrap = $(this),
            image = wrap.children('img:eq(0)'),
            width = image.height() * wrap.data('ratio');

        image.width(width);
        wrap.width(width);
    });
});

See the example in action

Answer №2

When it comes to the basics, there are three key elements to consider:

  • Ensuring an image (or its wrapping div) matches the height of its parent div
  • Maintaining the image's aspect ratio
  • Resizing the image based on the viewport height and width

After experimenting together, we found that a solution could not be achieved solely with CSS. This led me to propose the idea of obtaining the height of the parent div and applying it to the image.

This approach resulted in the following solution:

OPTION 1

By implementing the following jQuery snippet (along with a jQuery library), the image preserves its ratio when the window is resized:

$(function() {
  var height = $('.child-wrapper').height();
  $( ".image-wrap, .image-wrap img" ).css('height', height + 'px');
});

$( window ).resize(function() {
  var height = $('.child-wrapper').height();
  $( ".image-wrap, .image-wrap img" ).css('height', height + 'px');
});

You must also remove any dimensions specified in the CSS for .image-wrap and .image-wrap img, leaving you with:

.image-wrap {
  position: relative;
  display: inline-block;
  background: red;
  border: 1px solid blue;
}

.image-wrap img {
  vertical-align: middle;
}

JSFIDDLE

OPTION 2

If desired, you can incorporate box-sizing: border-box; so the border becomes part of the div rather than surrounding it. However, this may cause the image to overflow, necessitating the removal of 2 pixels (or the border thickness) from the image. This adjustment can be easily made using the following modified jQuery code tailored for use with box-sizing:

$(function() {
  var height = $('.child-wrapper').height();
  $( ".image-wrap" ).css('height', height + 'px');
  $( '.image-wrap img').css('height', height -2 + 'px');
});
    
$( window ).resize(function() {
  var height = $('.child-wrapper').height();
  $( ".image-wrap" ).css('height', height + 'px');
  $( '.image-wrap img').css('height', height -2 + 'px');
});

JSFIDDLE

Both of these examples require some fine-tuning to ensure they function as intended within your project.

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

Evaluate numerical values using xsl:choose function

Using XSL version 1.0, I am populating an HTML table with percentage values from XML. My goal is to display the highlighted color of the percentages based on a condition, but the condition is not being processed as expected, leading to the exclusion of the ...

Grid item overlay

Currently, I am facing an issue with React where I am attempting to place an overlay on top of each grid item in a grid. Despite trying multiple approaches, the overlay appears beneath each grid item instead of over it. Even setting the position: absolute ...

Adjusting the height of a CSS div to be 0 while also modifying the

I have encountered a unique dilemma <div class="parent"> <p>stuff stuff stuff</p> </div> Using CSS, I set the width and height of parent = 0; because I intend to modify it when a button is clicked. However, for this purpose, I ...

Unusual behavior exhibited by MUI Grid in the presence of spacing

I am working on a code snippet that looks like this: <Box sx={{height:'100vh', background: '#f5f7fc', overflow:'auto'}}> <Grid container justifyContent={'center'} padding={2}> <Grid item ...

Add a hyperlink within a button element

I am looking to add a route to my reusable 'button' component in order to navigate to another page. I attempted using the <Link> </Link> tags, but it affected my CSS and caused the 'button' to appear small. The link works if ...

Understanding the process of extracting map data from JSON files

I am currently working with Spring 3 and JQuery. My goal is to retrieve a Map containing element IDs and their values from my Spring Controller, and then use this data to update the View. Below is a snippet of the Controller code: @RequestMapping(value= ...

Is there a way to make the iOS Safari address bar shrink when scrolling, all while having a flexbox sticky footer inside a container?

I have implemented a standard flexbox sticky footer solution in my code: <body> <div class="wrapper"> <div class="header">Page Header</div> <div class="body"> <div class="b ...

Is there a way to specifically import only variables and mixins from Sass stylesheets?

Using the Zurb Foundation 4 (S)CSS framework has presented a challenge with massively duplicated styles. Each file that I import 'foundation' into brings along all of Foundation's styles, resulting in redundant declarations for body, .row, . ...

Transmit a document to the OpenAI API without the need to interact with the file storage system

Is there a way to send file data to the OpenAI API without directly accessing the file system? I have the file contents stored as a string and would like to bypass reading from the file system. The code provided in the OpenAI documentation involves reading ...

Having trouble directing input to embedded swf upon page load in Opera

I have created a basic HTML file designed to display embedded flash content immediately upon loading, without requiring any prior interaction. Unfortunately, I have encountered an issue in my preferred browser, Opera. The problem seems to be isolated to th ...

Acknowledge that a checkbox was found to be unchecked while editing a php/html form

Currently, I am in the process of developing a form using PHP/HTML that enables users to input data, review, and potentially edit their inputs before final submission. One of the key elements within this form is the use of checkboxes. Thanks to resources l ...

Display jqgrid with borders and insert extra headers text at the top of the grid

function generateTableWithText(){ $("#active_grid").jqGrid("exportToHtml",{ includeLabels : true, includeGroupHeader : true, includeFooter: true, autoPrint : true ...

Adding images sourced from the News API

I have successfully integrated an API from newsapi.org, and it's functioning well. However, the data I receive is only in text format and I would like to include images for each headline. I'm unsure of how to do this since the headlines are dynam ...

What is the process for extracting an array from an object?

How can I retrieve an object from an array using Node.js? I have tried the code below, but it's returning the entire object. What I actually need is to only print the name, for example, just "sethu". Code: var sethu = [{ name:'sethu', ...

Jquery Flexigrid at your service

Can someone help me understand how to implement Flexigrid jQuery on my website? Your assistance is greatly appreciated. ...

Sending a JSON object with scheduled task cron job

I have a PHP cron job that is quite complex. It retrieves data from an external webpage and consolidates all the information into one variable, encoding it in JSON. Unfortunately, this entire process is slow and consumes a significant amount of time. My d ...

Ways to guide user after logging out

My Angular front end includes the following code in app.js to handle user logout: .when('/logout', { templateUrl: 'mysite/views/logout.html', resolve: { authenticated: ['djangoAuth', function(djangoAuth){ return ...

Adjust date by one day using the Datetimepicker tool

I have been attempting to adjust the date of my input by one day either forward or backwards, but I seem to be stuck and not making any progress. Take a look at my code: function function backDay() { var date = $('input#datetimepicker').va ...

Using an Ajax Post Call to send FormData leads to a Get request instead

Having trouble with sending a simple form via POST method. I load the form content using AJAX: $(function() { var arg = { "operation": "upload", "step": "0" ...

Leading astray — using htmlentities will not function

UPDATE (Instead of deleting this question, I'll keep it as a reminder that errors are sometimes found in unexpected places...) I apologize for leading you down the wrong path with this question. The issue causing the "Actual result" was actually loc ...