Creating a dynamic overlapping image effect with CSS and JavaScript

My fullwidth div has an image that overlaps it. When the browser is resized, more of the image is either shown or hidden without resizing the actual image itself. I managed to get this effect for the width, but how can I achieve the same result for the height?

Here is the test I conducted: https://jsfiddle.net/g8h8umt3/

I successfully adjusted the width using CSS:

#img-header{
    margin-left: 50%;
    transform: translateX(-50%);
}

EDIT:

Here is an illustration of how it should work: Image

The background image should maintain its size while the parent div adjusts accordingly based on the screen size. I figured out the behavior for the width, but I'm unsure how to do the same for the image's height.

I also attempted to add:

#img-header{
    margin-top: 50%;
    margin-left: 50%;
    transform: translate(-50%,-50%);
}

However, this solution doesn't seem to be effective.

Answer №1

To achieve the image maintaining its size and being hidden on all corners as the parent's size changes, you can use absolute positioning for the image along with a combination of left: 50%; top: 50%; transform: translate(-50%,-50%) to center the image within the parent container. This way, the parent will scale proportionally around the image.

$(document).ready(function () {

$('#img-header-container').height($( window ).width()/3);

    $( window ).resize(function() {
onResized();
});
});

function onResized(){
$('#img-header-container').height($( window ).width()/3);
}
#img-header-container{
  width: 100%;
overflow: hidden;
  position: relative;
}

#img-header{
  position: absolute;
left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="min-height:50px">Conent Before</div>
<div id="img-header-container">
  <img src="https://clsimplex.com/images/releases/headers/quality-code.jpg" id="img-header"/>
</div>
<div style="min-height:50px">Conent After</div>

Also, instead of using jQuery to set the container height to one-third of the window's height, you can utilize viewport units (vh) along with calc() for a more streamlined solution.

#img-header-container {
  height: calc(100vh / 3);
  overflow: hidden;
  position: relative;
}

#img-header {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
<div style="min-height:50px">Conent Before</div>
<div id="img-header-container">
  <img src="https://clsimplex.com/images/releases/headers/quality-code.jpg" id="img-header" />
</div>
<div style="min-height:50px">Conent After</div>

Another approach is to use a background image instead of an img tag, reducing markup and CSS complexity.

#img-header-container {
  height: calc(100vh / 3);
  background: url('https://clsimplex.com/images/releases/headers/quality-code.jpg') center center no-repeat;
}
<div style="min-height:50px">Conent Before</div>
<div id="img-header-container">
</div>
<div style="min-height:50px">Conent After</div>

Answer №2

I'm not sure if I fully grasp your intentions Here is an example based on my interpretation

#main-image-container{
  width: 100%;
}

#main-image{
  max-width:100%;
}
<div style="min-height:50px">Content Before</div>
<div id="main-image-container">
  <img src="https://example.com/image.jpg" id="main-image"/>
</div>
<div style="min-height:50px">Content After</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

Delaying Ajax request

I've encountered some strange behavior. After the initial ajax call triggered by selecting a city from a dropdown menu, I then have a continuous ajax call on a delay. The first call stores the selected city value in a global variable. $('.sele ...

Methods for ensuring that fake browser tab focus remains on several tabs simultaneously

Is there a way to simulate multiple tab/window focus in a browser for testing purposes? I need to test pages that require user input and focus on active windows/tabs. Are there any different browsers, plugins, or JavaScript code that can help me achieve th ...

How to toggle a boolean variable in AngularJS when transitioning between states

Just getting started with AngularJS and trying to figure out how to tackle this issue. I have set up the following route: name: "Tracker", url: "/tracker/:period", and I have 3 distinct states for which I've created 3 separate functions to facilit ...

Reading multiple files in NodeJS can be done in a blocking manner, and then the

When retrieving a route, my aim is to gather all the necessary json files from a directory. The task at hand involves consolidating these json files into a single json object, where the key corresponds to the file name and the value represents the content ...

Dygraphs.js failing to display the second data point

My website features a graph for currency comparison using Dygraphs. Everything was working fine until I encountered this strange issue. https://i.stack.imgur.com/OGcCA.png The graph only displays the first and third values, consistently skipping the seco ...

The TypeScript inference feature is not functioning correctly

Consider the following definitions- I am confused why TypeScript fails to infer the types correctly. If you have a solution, please share! Important Notes: * Ensure that the "Strict Null Check" option is enabled. * The code includes c ...

Prevent user input in HTML

Currently, I am working on creating the 8 puzzle box game using JavaScript and jQuery Mobile. The boxes have been set up with <input readonly></input> tags and placed within a 9x9 table. However, an issue arises when attempting to move a box ...

I need help figuring out the right way to define the scope for ng-model within a directive

I found a straightforward directive to automate sliders: app.directive('slider', function() { return { restrict: 'AE', link: function(scope, element, attrs) { element.slider({ value: scop ...

What strategies does Wired magazine use to create their unique thick underline link style?

Recently, I came across an interesting design choice on Wired magazine's website - they use a thick blue underline for their links that crosses over text descenders and is a different color from the text itself. You can see an example on this random p ...

What is the best way to transfer information from a model to the screen?

I need assistance with adding a Todo using a model. When I click the Add todo button located at the bottom of the page, it opens the model. I want to be able to add whatever I type in the input field to the list. How can I send the input field data to the ...

Hey there, could you please set up the DateTimePicker in my expo project using React Native?

Hey everyone, I'm currently trying to set up DateTimePicker but encountered an error. Here's the issue: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: undefined@undefined npm ERR! Fou ...

Performing addition operations on numbers entered through an HTML input field using PHP

I am looking to create a feature where the numbers entered in an input form are added together. I need to store these numbers in an array and have them display in a new line when a button is clicked. Here is the HTML code for the input field and button: ...

Is it possible to use Javascript to gradually fade in text, one word at a time, with multiple divs instead of just one?

I am attempting to gradually fade in individual words from a div. While the code below works fine for a single div, it does not execute sequentially when multiple divs are involved. Here is the fiddle : http://jsfiddle.net/zlud/6czap/110/ Can anyone spot ...

Tips on altering the location path when redirecting to a different page using window.location?

Is it a silly question to ask? I tried looking for the answer on Google but couldn't find it. I'm currently working on a website where users can upload photos or videos, using HTML, CSS, and JavaScript. On the homepage, when a user clicks on a ...

Creating a new version of an existing method found within a component in a Vue store.js file

As I navigate through the learning curve of vue.js, a seemingly simple question has arisen: how can I achieve the following task? Within one of my vue components, I am facing challenges with the implementation of the "loadSuggestedUsers" method. Here is t ...

Locate an original identifier using Selenium WebDriver

In search of a distinctive identifier for the "update profile picture button" on my Facebook account to utilize it in automation testing with Selenium WebDriver and Java. I attempted driver.findElement(By.className("_156p")).click();, but unfortunately, i ...

Internet Explorer versions 9 and 10 do not support the CSS property "pointer-events: none"

In Firefox, the CSS property pointer-events: none; functions properly. However, it does not work in Internet Explorer 9-10. Are there any alternative approaches to replicate the functionality of this property in IE? Any suggestions? ...

Outputting HTML using JavaScript following an AJAX request

Let's consider a scenario where I have 3 PHP pages: Page1 is the main page that the user is currently viewing. Page2 is embedded within Page1. It contains a list of items with a delete button next to each item. Page3 is a parsing file where I send i ...

Remove padding in Twitter Bootstrap table cells

One of my current projects requires making a button that fills the entire width and height of the TD element. I have attempted setting the normal .btn-warning with -Xpx!important, but it did not produce the desired result. Here is what I currently have: ...

Retrieving data from an HTML webpage using VBA

In my attempt to access the "username" cell from a web page using VBA, I encountered an issue. The HTML code of the page contains multiple elements with the same name, "LOGON_USERID", making it challenging for me to identify and access the correct one. Hi ...