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

The ng-click event in AngularJS does not function as expected when nested within another ng-repeat loop

I am facing an issue with ng-click in my Angular application (version 1.0.4). The first ng-click works fine, but the second one does not. <div class="menu-group" ng-repeat="module in modules"> <div ng-click="toggle($event, $parent)" ...

What is the process for adjusting the color of a div?

Is there a way to adjust the background color of a div when hovering over another div in HTML? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.or ...

"Using axios and async/await in VUE.JS to perform multiple asynchronous GET

Perhaps this is a somewhat basic inquiry, as I am still learning the ropes of vue.js and javascript. Please bear with me if my question is not well-articulated or if the solution is straightforward... I am facing an issue where I need to retrieve data from ...

Issue with Bottle.py: When using AJAX, request.forms.get() is returning NoneType

Having trouble sending JavaScript data to a bottle.py server using AJAX? Despite trying numerous solutions from various sources, none seem to be working. To provide clarity, I'm focusing on the AJAX call code here. Can someone explain why request.for ...

Challenge with Context Api state not reflecting the latest changes

Hey there, I've got this function defined in AuthContext.js: let [authTokens, setAuthTokens] = useState(null) let [user, setUser] = useState(false) let [failedlogin, setFailedlogin] = useState(false) let loginUser = async (e) => { ...

Reactjs is retrieving several items with just one click on individual items

I am having trouble getting only a single sub-category to display. Currently, when I click on a single category, all related sub-categories are showing up. For example, in the screenshot provided, under the Electronic category, there are two subcategories: ...

CSS hover effects are malfunctioning

Having an issue with hover in CSS. Attempting to create a menu bar using saved PNG files, each file within its own div. When applying a class name and hover modifier, it only works on the first element. As the pointer moves to subsequent elements, they are ...

Steps for achieving a seamless transition in jqueryui

I currently have a jQuery toggle function that removes several divs from a webpage: $("a#list-mode").click(function() { $("a#list-mode").toggleClass("rm-toggle"); $("a#map-mode").toggleClass("rm-toggle"); $("div.rm-ta").t ...

Material-UI's simplification of 10px comprehension

I'm a bit confused about why we have to do this for the 10px simplification: html { font-size: 62.5%; /* 62.5% of 16px = 10px */ } Shouldn't the following code handle everything? const theme = createMuiTheme({ typography: { // Set the ...

What is the best way to extract the value from a Material UI Slider for utilization?

I am looking to capture the value of the slider's onDragStop event and store it as a const so that I can use it in various parts of my code. However, I am unsure about how to properly declare my const sliderValue and update it. Any guidance on where a ...

picture protrudes from the frame [WordPress template]

Check out my website: If you scroll to the bottom of the site, you'll see an image of a bride sitting on a couch. I recently added this code to the stylesheet: .novia img {min-width:1000px; float:none;} This code was meant to maintain a fixed heigh ...

Displaying incorrect symbols with icon fonts

I have successfully integrated icon fonts into my simple web page. Check it out on jsFiddle here My design is similar to this example, but instead of bars, I see a snake icon displayed. How can I fix this issue with the fonts? Here is the code snippet: ...

Extract all class elements from HTML code and save them to a text file using PHP

Is there a way to extract all span elements with the class "msgsource" from my website's HTML code and then save it as a .txt file for downloading? I tried using the following code, but it only downloads an empty text file: <?php // Grabbing conte ...

Obtain the latest NPM package versions

I am currently seeking a way to compile a comprehensive list of all major versions that have been released for a specific NPM package. By utilizing the following API link, I can retrieve a list of available versions which includes both the major and exper ...

Disappearing White spaces in a Java Swing Label with HTML TagsIn a Java

I'm facing an issue where coloring one character in a string causes most of the whitespaces to disappear. I'm puzzled as to why this is happening and if there's a viable solution? map[9] = "# # ...

Exploitable Weakness Found in NestJS Version 8.4.5

After running npm audit on my npm package recently, I encountered an error that is related to the dicer package, widely used by NestJS. I have looked for solutions online but haven't been able to find any fixes so far. Has anyone else managed to reso ...

Exploring JavaScript and Node.js: Deciphering the choice of prototype.__proto__ = prototype over using the

Currently exploring the Express framework for node.js and noticed that all the inheritance is achieved through: Collection.prototype.__proto__ = Array.prototype; Wouldn't this be the same as: Collection.prototype = new Array; Additionally: var ap ...

Having trouble locating the bootstrap import statement

Currently, I am working on a project in Angular where I have defined two styles in the angular.json file - styles.css and node_modules/bootstrap/dist/css/bootstrap.min.css. After running ng serve, it shows that it compiled successfully. However, upon ins ...

Can you explain the concept of "Import trace for requested module" and provide instructions on how to resolve any issues that

Hello everyone, I am new to this site so please forgive me if my question is not perfect. My app was working fine without any issues until today when I tried to run npm run dev. I didn't make any changes, just ran the command and received a strange er ...

Exploring the Positives and Negatives of Using JQuery and Glow JavaScript Libraries

Is there a detailed analysis available that compares JQuery with the BBC's Glow JavaScript libraries? ...