What is the best way to place a floating elastic div on top of an elastic background and ensure that the div stays in place?

Looking for some creative input here. Don't have a specific question in mind, but open to ideas.

Just to clarify, I want both the floating div and the background to resize as the window size changes, while keeping the div in the same position on top of the background.

Do you think this is achievable?

https://i.sstatic.net/g62gq.png

Check out this jsFiddle link for reference: http://jsfiddle.net/778fb958/3/

<div class='background'>    
    <div class='foreground'>
        <img class='tinyguy' src="http://orig05.deviantart.net/2f16/f/2012/027/8/9/16_bit_mario_by_nathanmarino-d4ntfl6.png">
    </div>    
</div>

Answer №1

Implementing percentages is crucial.

Utilize the position attribute to achieve this.

Review this demonstration utilizing position: absolute; and setting top and left to 20%.

Check out this illustration without specifying a position, but adjusting margin-top and margin-left</code to <code>20%

Observe how the background incorporates this ...

.background {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

... to cover the entire screen

Answer №2

Your specific scenario isn't entirely clear to me, but utilizing viewport units may be beneficial:

//Utilize viewport units for background size
#background {
  width: 100vw;
  height: 100vh;
}

//Create a square div that occupies 20% of the viewport size and is centered at 50% of the background from the top and left
#div {
  position: fixed;
  left: 50vw;
  height: 50vh;
  width: 20vw;
  height: 20vh;
}

Answer №3

Fixed positioning addresses numerous challenges by keeping the specified div in a set position relative to the window it is being viewed in.

If you wish to display the fixed div in relation to another div's position, you will need to utilize JavaScript to make it scroll along with user scrolling.

body { margin:0px;padding:0px;}
#background { 
  width:100vw;
  height:100vw;
  
  display:block;
  margin:0px;
  padding:0px;
    background-image:url(https://i.sstatic.net/phmE7.jpg);
    background-position-x: center;
    background-position-y: bottom;
    background-repeat: no-repeat;
    background-attachment: scroll;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
  
}
@media screen and (orientation:portrait) {
    #background {
        background-position-y: top;
        -webkit-background-size: contain;
        -moz-background-size: contain;
        -o-background-size: contain;
        background-size: contain;
    }
}
#header {
  width:100%;
  height:150px;
  background-color:red;
  color:white;
  font-size:4em;
  position:fixed;
    font-family:sans-serif;
    text-align:center;
    top:0px;
  left:0px;
  }
<div id="background">
  <div id="header">
  Perhaps... it's extraterrestrials
    </div>
  </div>

Answer №4

In my latest project, I created a JavaScript function to dynamically resize a div based on the original background size. I implemented this function to trigger on page load and on the "resize" window event using jQuery.

Take a look at the code snippet below. It may seem a bit messy and in need of some cleaning up, but I believe it can be helpful to anyone who comes across it.

https://jsfiddle.net/Nat/2a0ggcLs/

function resizeDiv() {
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;

//original background image size
var bgWidth = 1000;
var bgHeight = 667;

//position of element in relation to original background size
var topPosition = 220;
var leftPosition = 620;

//size of element in relation to original background size
var elementWidth = 100;
var elementHeight = 200;

//for vertical screens
if ((windowHeight / windowWidth) > (bgHeight / bgWidth)) {

    //resize
    document.getElementById("element1").style.width = ((windowWidth / bgWidth) * elementWidth) + "px";
    document.getElementById("element1").style.height = ((windowWidth / bgWidth) * elementHeight) + "px";

    //position
    var adjustedHeight = (windowWidth * (bgHeight / bgWidth));
    var posY = (topPosition * (windowWidth / bgWidth)) + ((windowHeight - adjustedHeight) / 2);

    document.getElementById("element1").style.top = posY + "px";
    document.getElementById("element1").style.left = (leftPosition * (windowWidth / bgWidth)) + "px";

} else {
    //for panoramic screens

    //resize
    document.getElementById("element1").style.width = ((windowHeight / bgHeight) * elementWidth) + "px";
    document.getElementById("element1").style.height = ((windowHeight / bgHeight) * elementHeight) + "px";

    //position
    var adjustedWidth = (windowHeight * (bgWidth / bgHeight));
    var posX = (leftPosition * (windowHeight / bgHeight) + ((windowWidth - adjustedWidth) / 2));

    document.getElementById("element1").style.left = posX + "px";
    document.getElementById("element1").style.top = (topPosition * (windowHeight / bgHeight)) + "px";

}

}

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

Python script for downloading audio files loaded with JavaScript

I am currently working on a Python script to automate the process of downloading English audio files from a specific website. When I click on the play button, the audio file starts to load and play, but I am unsure how to capture and download the file in ...

Is it better to have a heading titled "Navigation" above a <nav> element, or should it be included inside the navigation element itself?

Which is the better way to structure navigation: <h1>Navigation</h1> <nav> <ul> <li>...</li> </ul> </nav> Or: <nav> <h1>Navigation</h1> <ul> <li>...</li> ...

Maximizing the potential of $urlRouterProvider.otherwise in angular js

I am encountering an issue with redirecting to the login screen when there is no UABGlobalAdminId in my storage. I have tried using $urlRouterProvider.otherwise but it doesn't seem to be functioning properly. When I attempt to debug, the console does ...

AngularJS - issue with directive functionality on dynamically inserted classes

Check out this plnkr - I've got a button that toggles the class toggled on the body element. I've also developed a directive to trigger an alert when the toggled class is applied to the body element, but for some reason it's not working. H ...

Synchronous: Establishing a connection to MongoDB once the server has successfully launched

I am curious to understand the interaction between Node.js asynchronous functions and MongoDB. If the server initializes before establishing a connection, and if my templates or Ajax requests rely on database data, will the serving of the HTML fail or will ...

What is the most effective way to incorporate animated hyperlinks?

I've been grappling with a webpage I'm designing, featuring sentences acting as links arranged in inline-block format. My goal is to create an animated effect that resembles twinkling stars, pausing the animation on hover. It feels like I'm ...

"Exploring the World of Mobile Development and Screen Size

Currently, I am in the process of creating a basic mobile website that can be accessed through a QR code leading to the page linked below. However, I have encountered an issue where viewing it on my Android or Apple phone results in excess width. Any advic ...

Steps to enable overflow: 'scroll' for components generated dynamically

When developing a React application, I encounter an issue with creating new components dynamically inside a container. The problem arises when the height of the container gets exceeded by the newly added items, and I aim to make the container scrollable in ...

Removing the Bootstrap-container is a task that can be specifically targeted for larger screens

I need assistance with removing the container from my large screen while keeping it on small and medium screens. I have tried searching for a class like container-lg-none, but to no avail. Any help would be greatly appreciated. Here is the code snippet i ...

Are the maps intersecting within the field of vision?

I have 2 components in my angular application each showing a map from mapbox. Here is the code for one of the components: Component import { Component, OnInit } from '@angular/core'; import * as mapboxgl from 'mapbox-gl'; @Component( ...

No results are being returned by karma.js after setting up a basic "karma init" configuration

Currently, I am working through the tutorial "Introduction to Karma" on egghead.io which can be found here. To set up Karma on Windows, I followed these steps: > npm install --g karma-cli > npm install karma karma-jasmine karma-chrome-launcher --sav ...

The original items are not utilized by jquery-ui autocomplete

I currently have the following setup: class Team { constructor(data) { this.id = data && data.id || null this._title = data && data.title || null } get title() { return this._title } set title(v) { this ...

Are you attempting to retrieve the most up-to-date trading price of a stock with Python?

After attempting to extract the LTP of a stock with the code below, I am not getting any value in return. Can you identify the error in the following code: from selenium import webdriver from bs4 import BeautifulSoup driver=webdriver.Chrome("C:&bsol ...

Develop interactive, reusable custom modals using React.js

I am currently working on creating a reusable modal: Here is my component setup: class OverleyModal extends Component { constructor(props) { super(props); } openModal = () => { document.getElementById("myOverlay").style.display = "blo ...

The request for http://localhost:3000/insert.js was terminated due to a 404 (Not Found) error

As someone new to web development, I am currently tackling a project where I'm having trouble loading the Javascript file insert.js. The HTML document upload.html resides in the public folder, while the Javascript file is located in the main folder. I ...

Image not appearing on basic HTML website

This particular issue has left me completely puzzled. After removing all the unnecessary elements from a problematic website, I am now left with an extremely basic and minimalistic site: <!DOCTYPE html> <html lang="en"> ...

Troubleshooting Database Saving Problem with Vue.js and Ruby on Rails

Trying to configure a nested form with Vue.js in a Rails application to save ingredients for a recipe. While all other details of the ingredients are saving correctly, the ingredient name (from an input field) is not getting saved in the database. How can ...

"Utilize Bootstrap Flexbox for centering and aligning

I'm having trouble centering my navigation items and positioning my button at the end. I was able to move the button to the end, but I can't seem to figure out how to center the items and brand. Any assistance would be greatly appreciated! < ...

Utilizing the p tag to incorporate dynamic data in a single line

I am currently working with two JSON files named contacts and workers. Using the workerId present in the contacts JSON, I have implemented a loop to display workers associated with each contact. The current display looks like this: https://i.sstatic.net/AR ...

Flask Pagination : UnboundLocalError occurs when trying to reference a local variable 'res' before it has been assigned

I'm currently troubleshooting an issue with flask pagination. Whenever I attempt to implement it, I encounter the UnboundLocalError. Even after removing all variables, the pagination feature still fails to function as intended. @app.route('/&apos ...