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

Hovering over triggers tooltip flickering with Mouseover/Mouseenter interaction

When the mouseover event is triggered on the parent element, there seems to be a flickering issue when moving into the tooltip (child) element. The console log indicates that the mouseover/mouseenter event is being fired rapidly. The tooltip does not stay ...

When using the POST method to modify data via an HTML form, the previous values may be

I am currently developing a CRUD system and focusing on the Update functionality. My task involves updating existing user data with new information submitted through an HTML form. At this stage, I am working on retrieving the POST values from the HTML for ...

Combining nested lists with the tag-it plugin from jQuery, you can create a list inside a list all

Currently, I am utilizing the Tag-it jQuery plugin found at Tag-it, which functions within a ul element. Within my horizontal list (a ul with multiple li elements), I aim to add another li element containing the Tag-it ul list alongside the main horizonta ...

Having trouble accessing the root route in production environment

After creating a basic Node application with 5 routes that serve different HTML documents, I encountered an issue. While all the routes function properly when running on localhost, in production my root route displays a 404 error page, indicating that the ...

Error encountered during Atom execution - The command '/usr/bin/env: 'node' was not found in the directory

Just starting out with coding on Atom and I'm stuck dealing with the same error message every time I try to run my Javascript code. bash: line 1: node: command not found /usr/bin/env: ‘node’: No such file or directory I've searched for solu ...

Displaying a DIV after entering text into an <input> field using JavaScript

Attempting to create a JavaScript function that will show/hide a 'DIV' after entering some text into an input field. I have successfully written the function, but I am struggling to make it only work when the user enters a value greater than 8. ...

Is it possible to use window.print() to print the entire contents of a DIV with both horizontal and vertical scroll bars?

In my code, I have a div that contains both horizontal and vertical scrollers. Whenever I try to print the content inside this div using the window.print() method, it only prints the visible portion of the div. Here is the code snippet that I have attempte ...

How can you adjust the div orientation for small screens using Bootstrap?

I've been working with Bootstrap and I'm facing an issue with the orientation of a div on small screens. On medium screens, I have two columns set to 6, 6 which should stack on top of each other on smaller screens. Here's how I want it to lo ...

What are the tips for aligning this button perfectly on the page, despite being centered in a computer's resolution?

Dealing with Responsive Design Hey there! I'm having an issue with my Bootstrap layout. I managed to center a button, but when I adjust the resolution or make it smaller, the button wraps and shifts to the right. Can anyone help me figure out what we ...

Steps for inserting a clickable phone number link within innerHTML1. First, create an

I've been trying to include a specific phone number using the <a href> tag within the innerHTML. I attempted using both double and single quotes. In the first case, nothing happens at all. In the second case, although the phone number appears, ...

What is the best way to access a variable from a different function in JavaScript?

In my current project, I have implemented a function that fetches a JSON string from an external URL. The JSON data is being retrieved successfully and is functioning as expected. However, I am facing an issue with the variable 'procode'. I need ...

Is the PHP configuration correct for Apache on your local server?

I'm currently facing an issue with connecting to a MySQL server in order to retrieve data for a flash application using PHP. I created a test .php file to check if everything is working correctly: <html> <body> <?php $link = mysql_con ...

Automatically populating state and city fields with zip code information

Starting out in the world of web development, I encountered a challenge with a registration form I'm constructing for our company. For guidance, I referred to this resource: http://css-tricks.com/using-ziptastic/. This project marks my initial interac ...

Out of Sync Promise Chain

I recently encountered an issue with promise chaining in JavaScript, specifically while working with Vue.js. Here is my code: I have an addItem function that inserts an item into the database. My goal is for this function to first insert the data into the ...

The difference between invoking a method directly and utilizing a function to invoke a method

Imagine we have a method inside a class that looks like this class Blog extends Component { postClicked = (id) => { this.setState({selectedPostId: id}) } render () { const newPosts = this.state.posts.map(el => { return & ...

Is it possible for Prototype to enhance SVG components?

Having some issues developing an interactive SVG map with Prototype. Extending inline SVG elements seems to be causing problems. Take a look at my code snippet below (path data removed for brevity): <svg id="map" xmlns="http://www.w3.org/2000/svg" xmln ...

Is it acceptable to post variables using AJAX for processing?

Is there a way to send data with AJAX using the code provided? It seems like the information is not being sent to the PHP file as intended. Here is the code snippet: $('#send').click(function(){ var pseudo = $('#psd').val(); }) ...

Ways to ensure that an element is aligned within a parent div with a 100% bottom position

I am facing a small issue that I need help with. My problem is aligning an element to the top of a percent div with bottom: 100%, and I just can't seem to make it work within the parent div. Essentially, I want bottom: 0% to align with the bottom of ...

dividing Handlebars HTML content into different files or sections

I am looking to design a single route webpage, but I would like to divide the HTML code into multiple files. When rendering this particular route, my goal is for the rendered file to pull content from different template files and combine them into one coh ...

Using axios to make a request to a REST API

I recently developed a Rest API using express to interact with mongodb. Testing it with postman has been successful so far. However, when I attempted to integrate the api with a basic web app created in vue and used axios to get a response from the api, ...