Adjust and place div in relation to image with full height perspective

Looking for a better headline...

On my non-mobile device page, I want to ensure that a large image always fits the window height. Take a look at the page.

This is how I've set it up:

#background{
    position:absolute;
    background-color:#F00;
    width:100%;
    height:100%;
    top:0%;
    background-image:url(Ortsplan_2014_small.jpg);
    background-size:contain;
    background-repeat:no-repeat;
    background-position:center;
}

It appears as shown in the link to the "Page".

However, when I resize the window to test on different screens, the green div box behaves strangely. Check out this image to see what happens or try scaling the window yourself.

Here is the code for the div box:

#hotspot-nickelsee{
    position:absolute;
    background-color:#0F0;
    top:25%;
    width:10%;
    height:10%;
    left:33%;
}

And here is the HTML-Code:

<div id="background">
     <div id="hotspot-nickelsee">
     </div>
</div>

What am I doing wrong here? How can I make sure the div box stays in the same position on the image regardless of window size? Any tips?

When I try loading the image directly into the "background" div instead of using it as a background picture, the div scales to 100% of the image size and fills the window, which is not the desired outcome.

Thank you for any assistance!

Answer №1

Managed to accomplish it using Javascript.

<script>
jQuery(document).ready(
    function()
    {   

        var background=jQuery('#background');  //selecting the div
        var image_aspect_ratio=1500/2500; // aspect ratio of the image

        function resize_image() {  // function to modify the div

            var viewportHeight= jQuery(window).height();  // viewport height
            var div_width=Math.ceil(viewportHeight*image_aspect_ratio);  // div height = viewport height; div width = viewport height * aspect ratio 
            background.css("width",div_width); // setting width

        };
        resize_image();  // calling the function without an event handler for the first time
        jQuery(window).resize(resize_image);  // this event handler is triggered on every resize, which then calls the function again


    });
</script>

Everything is functioning as expected in this manner. Appreciate your assistance regardless!

Answer №2

The issue stemmed from the #background div, which covered the entire width and height of the body, causing problems when resizing the window as it affected the positioning relative to #background. To address this, #background needed to only cover the size of the image, requiring the image to be enclosed within an img tag for proper fitting. Implementing a technique known as shrink wrapping was necessary in this case.

To achieve the desired layout, additional HTML elements were introduced with some CSS modifications. Notably, setting the display property of #background-container to inline-block allowed for centering the image using text-align: center. The use of margin: 0 auto for centering was not applicable due to the inline-block display setting.

Below are the updated HTML changes:

<div id="background-color">
  <div id="background-container">
    <div id="background">
      <img class="background-image" src="Ortsplan_2014_small.jpg">
         <div id="hotspot-nickelsee" class="hotspottet">
         </div>

         <div id="hotspot-marienkapelle" class="hotspottet">
         </div>

         <div id="Hotspot-Kirche" class="hotspottet">
         </div><div id="Hotspot-Kirche2" class="hotspottet">
         </div>

         <div id="Hotspot-Stadtmauer" class="hotspottet">
         </div>

         <div id="Hotspot-Rathaus" class="hotspottet">
         </div>

      </div>
  </div>
</div>

And here are the adjusted CSS styles (comments indicating removed code should also be deleted):

.background-image {
    max-height: 100%;
}

#background-color {
    position: absolute;
    background-color: red;
    width:100%;
    text-align: center;
}

#background-container {
    display: inline-block;
}

#background {
    position: relative; /*changed from absolute*/
    background-color: #F00;
    display: inline-block;
}

Give these updates a try. They worked well for me during testing in the browser. If you encounter any difficulties or require further assistance with implementation, feel free to reach out by commenting below.

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

What is the best way to generate hyperlinks for hidden content controlled by a show/hide javascript function?

I am interested in creating links to hidden content using a show/hide JavaScript. Within the hidden content, there are three divs containing videos and text that I would like to link to. For example, linking to the "example" div as shown below. The links d ...

Tips for altering the placeholder color in Angular Material?

Currently, I am working with Angular 9 and Angular Material version 10.2.0. This is the code that I have: <mat-form-field> <input matInput type="text" name="" placeholder="title" id="title" [(ngModel)]=&q ...

How can I utilize JavaScript to seamlessly loop through and display these three images in succession?

My current code is HTML, CSS, and JS-based. I am looking to design three of these div elements that appear and hide in a loop every 3-5 seconds. After the first run, I want the execution to repeat continuously. How can I modify my code to achieve this func ...

Best Practices for Prioritizing CSS Selection

My usual practice is to organize the rules in my CSS file to align with their corresponding elements in the HTML code. However, when it comes to global rules such as styling for input,textarea,p,tr,th, and so on, I wonder if there is a specific convention ...

Looking for tips on how to achieve a sleek search bar expansion effect when focusing using w3.css?

I have been trying to utilize the following code to create a Google search bar that expands when focused within a w3.css navigation bar-item. While it does expand and contract on focus/blur, I am unable to achieve smooth transitions between sizes. The sear ...

Applying CSS transitions and transforms to SVG elements

Having trouble animating an SVG group with CSS transitions after applying a CSS transform? Check out my code below and let me know if you spot the issue. Inline SVG Code <a href="javascript:void(0)" class="hub-icon-container"> <svg xmlns="ht ...

Press and hold feature using CSS or JavaScript

When working with a jQuery draggable element, my objective is to change the cursor to a move cursor when clicking and holding the header. I have attempted using CSS active and focus properties, but so far no changes are taking place. ...

Conceal particular information within a repeated sequence and reveal it within a secret panel

I am working on a component that needs to show a hidden form when a specific content is clicked. I have successfully achieved this functionality, but now I also need to hide the original content div and display the hidden form in its place without affect ...

Show singular array element upon click

I need help with a specific task. When a button is clicked, I want to display a random item from an array. Each array item should only be displayed once. Currently, my code is set up as follows: When the button is clicked, a random array item is displ ...

Styling an unordered list with CSS in HTML is a powerful

I am working with an unordered list where each list element contains two spans: span A and span B. My goal is to style these elements so that they are displayed horizontally on the screen, with span A above span B in each set. Example: spanAItem1 sp ...

Enclose a group of tiles in a shrinkwrap div

I've been struggling to make a div adjust to its content size here. I've attempted various methods to shrinkwrap it, but none seem to work. <div class="outer"> <div class="cont"> <img src="http://www.placehold.it/100" ...

Highcharts 3D Pie Chart with Drilldown Feature

How can I create a 3D Pie Chart with Drilldown effect? I am having trouble understanding how it works. Here is a JsFiddle Demo for a 3D Pie Chart: JsFiddle Demo And here is a JsFiddle Demo for a 2D Pie Chart with Drilldown feature: JsFiddle Demo You can ...

Using Jquery to Switch Pages

Recently, I've been experimenting with using hashes to create animated transitions between pages. Interestingly, the first page that loads (the home page) fades in and out seamlessly. However, when I attempt to navigate to another page, specifically t ...

CSS animation causing font-size rendering issues

I attempted to create a sentence where specific words are animated (rotated through) - initially it seemed to be working fine. However, upon checking the site on my mobile device, I discovered an issue. When accessing the page from a desktop ( including wi ...

Experiencing difficulties with the background color of a child div in HTML while using Yahoo

My dynamic "progress bar" component has the ability to render various background colors and widths based on different percentages. Here's a snippet of the code: <div style={{ backgroundColor: '#FFFFFF', height: '24px' ...

What is the best way to highlight titles that are unique but still prominent?

.test{ display:none; } .title:nth-child(odd){ background: #ddd; } <div class='title'>lorem</div> <div class='title'>lorem</div> <div class='title test'>lorem</div> <div class='tit ...

Creating a dynamic navbar in an ASP.NET website by populating it with data from a

Seeking guidance on creating a dynamic Bootstrap navbar in an ASP.NET website based on the user's role stored in a database, while maintaining the same style. I have extensively searched for a solution without success. Any assistance would be greatly ...

What are the steps to modify the text color in WKWebView?

I've customized my ViewController to include a WKWebView, where I load my content from both .html and .css files. The result resembles a controller for reading books within the Apple Books app. do { guard let filePath = Bundle.main.path(fo ...

How to Toggle Div Visibility with AngularJS ng-show and ng-click

In order to eliminate error messages, I decided to clear the field with a button click. This approach successfully removed the error in my initial test. <div class="errorPopup" data-ng-click="runner.Name = null" data-ng-show="mainForm.name.$error.pat ...

Is there a way to rotate a div to exact coordinates?

I am working with two (or perhaps three) coordinates. These coordinates represent the upper left and upper right corners of a shape. My goal is to create a div element where the top-left corner corresponds to the left coordinate, and the top-right corner ...