Changing the position to fixed causes the image to resize as you scroll

I am trying to achieve a fixed image effect when it appears on the screen during scrolling, but I want it to return to its normal position if the user scrolls back up. The issue I'm facing is that when I use a JavaScript function to change the image position to fixed during scroll, it suddenly jumps or resizes, and I'm not sure why. My current workaround involves creating variables to adjust the width and left values of the image after fixing it, but this solution seems to be unique for each image on the page. I'm struggling to understand the underlying concept causing this problem. Simply resetting the width and left values to their original state does not seem to work. Does a fixed position resize an image?

Here is a jsfiddle showcasing the issue along with the code snippet below:

 var sitckyImageWidth = "38.4%";
  var normalImageWidth = "48%";


document.addEventListener("scroll", function(){

  var windowTop = $(window).scrollTop();
  var  windowWidth = window.innerWidth;
  var  windowHeight = window.innerHeight;

   //loop through each div and grab top/bottom/midpoint info and find id
   $('.articles').each(function(i){
     var top = $(this).offset().top;
     var bottom = top+ $(this).height();
     var midPoint = (bottom+top)/2;
     var thisId = this.id;
     var newId;

    //use container div info to find media info
     var newId = thisId+"Media";
     var sectionImage=document.getElementById(newId);
     var sectionImageTop = $(sectionImage).offset().top;

      //if article is on the page, change position to fixed and set top position
     if (top<=windowTop&&bottom>windowTop){

       $(sectionImage).css("top","10px")
       $(sectionImage).css("position","fixed")
       //$(sectionImage).css("width",sitckyImageWidth)
     }
      //if container is not at top of the page, return to relative
     if (bottom<=windowTop||(bottom>windowTop&&top>windowTop)){
       $(sectionImage).css("position","relative")
     }
   })
}); //end scroll

Answer №1

When an element has a position fixed, its sizes and placement are determined in relation to the viewport rather than its parent elements.

In this particular case, the div with the ID article1Media is set to have a width of 48%. When it is positioned relative, this translates to 48% of the width of its containing element (the div with the ID article1). However, when it is set to position fixed, it becomes 48% of the viewport width. This difference is due to the implicit 8px margin on the <body> element.

There are several ways to address this issue, depending on how you want to structure your website.

Solution 1:

To quickly fix the immediate problem, you can add the following CSS:

body{
    margin:0px;
}

.image{
    margin:8px;
}

You can adjust the margin value as needed or remove it altogether.

For more information on overriding default styles, consider looking into CSS resets, but be cautious not to overdo it.

Solution 2:

Another approach could involve setting fixed dimensions using jQuery's .width() and .height() functions. While less flexible and responsive, this method may be suitable in certain scenarios.

Solution 3:

A more adaptable solution might entail using fixed widths alongside CSS media queries for responsiveness. For example:

.image{
    width:500px;
}

@media(min-width:800px){
    width:300px;
}

Solution 4:

If you prefer percentage-based fluid layouts, consider exploring the use of calc with an added offset when applying a fixed position. This would allow for dynamic sizing adjustments when the image is fixed:

.media.image-fixed{
  position:fixed;
  width:calc(48% - 8px);
}

Check out this demo for reference: https://jsfiddle.net/Chipmo/6mu2Lt9g/2/

Answer №2

The reason for the observed behavior is due to the application of the position property, not because of scrolling. For more information, refer to this link: Position Properties
Fixed Position: Elements with fixed positioning are relative to the document and not any parent container, occupying the full available width. Relative Position: Elements with relative positioning behave in relation to their containing containers, with inner elements consuming the width of the parent container.

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

Adjusting the width of rows in tables for th and td elements

Hi there, I'm having trouble with aligning the data inside a table. The table alignment seems off, and I'm struggling to fix it. Can anyone lend a hand with this? The only thing I can't remove is the height: calc(100vh - 346px); as it's ...

Hop over to another page within the same blog on Blogger with a smooth scrolling feature and automatic redirection

I am looking to enhance my blog by implementing a feature where if someone clicks on a specific link, they will jump scroll to a designated point on the same page. After a few seconds, I want them to be automatically redirected to another page within the s ...

What is the best method for performing shape subtraction in CSS?

Is there a way to create a frame with a border radius of '150px 30px 30px 30px', but have the top left corner flat instead? See the image for reference here. I tried using a rotated rectangle in the ::before pseudo element to achieve the desired ...

Error: Unable to locate the tslint command

After attempting to utilize tslint --fix, I encountered the error message bash: tslint: command not found.... To install tslint, I ran the following command: yarn global add tslint typescript. The operating system on my machine is Centos 7. ...

Is it possible to tap into the stylus Abstract Syntax Tree (AST) for

Is there a way to access the abstract syntax tree (AST) of the CSS style generated by stylus without re-parsing it using css-parse? I'm curious if the AST of the generated styles can be accessed publicly. ...

Trouble implementing array filter in React component is a common issue

Hello everyone! I'm facing an issue with deleting an element from my useState array. I have the index of the element that I want to remove, and I've tried the following code snippet: const updatedArray = myArray.filter((item: any, index: number) ...

The for loop GET request is not successfully pushing data to MongoDB, leaving the database with no entries

My current challenge lies in transmitting data from my for loop to MongoDB. Upon executing the js file using node initCount.js in the console, no errors are returned and everything seems to be working correctly. However, upon checking my MongoDB backend, I ...

Guide on incorporating a rating and review feature into your Windows 8 store app with JavaScript and HTML

Looking for assistance on integrating a rate and review feature into a Windows 8 store app using javascript and html. Specifically, I would like to add this option to both the charm settings and the app bar. When a user clicks on it, they should be directe ...

Certain .wav files may have trouble playing

Can anyone shed light on why certain .wav files refuse to play in Google Chrome Browser? Is there a workaround for playing .wav files only through Google Chrome Browser? ...

Error message: An error occurred while executing the AJAX PHP code due to a TypeError, specifically stating that the property 'status' cannot be

For some reason, I keep receiving an undefined return for my response. The event handler in index.php triggers the following code: $.post("getData.php", onNewPost()); function onNewPost (response){ if (response.status == "OK") { console.log(resp ...

Understanding image sizes for uploads on Tumblr can be a bit confusing, especially when comparing pages to posts. Learn how to implement lazyloading for post

I'm currently working on a highly customized Tumblr account that features a mix of pages and posts. I am looking to access content and assets, particularly images, from these pages/posts for use in other parts of the site. When I upload an image to a ...

Adding information directly into the <li> element

I'm feeling a bit unsure about the semantic correctness of this code snippet: <ul> <li>Winter</li> <li>Summer</li> </ul> While I understand that the <li> tag can contain any type of content, both block ...

Angular, display the chosen option within the text input field

Currently, I have a table with multiple columns and I am using Angular JS to display their values in various controls. For instance, I am using a Select/Option (multiple) to display column A, and I want to use another text box to display column B based on ...

Navigating between two HTML files in an ExpressJS project can be easily achieved by setting up routes

Recently delving into expressjs, I am struggling to navigate between two HTML files within the root folder. My project involves utilizing Bootstrap, AngularJS, and ExpressJS. In the routes directory, I have implemented the following code: var express = r ...

How can I overlay a background image on top of another div?

This inquiry might not be the most trendy, but I am seeking guidance on the best approach to tackle this task, utilizing HTML, CSS, and Bootstrap. For reference, something similar to the image at this link. ...

Struggling to make the height attribute work in Bootstrap 4 alpha

I'm currently in the process of learning Bootstrap, and I've encountered an issue with the height attribute in version 4 (for example: "row h-25") not functioning properly. I attempted to add another CSS rule that sets the height of "container-f ...

scrollable material ui chips list with navigation arrows

I'm attempting to create a unique scrollable chips array using Material UI version 4 (not version 5). Previous examples demonstrate similar functionality: View Demo Code I would like to update the scrolling bar of this component to include l ...

`The font appears extremely thin when viewed on Safari and iOS devices.`

I'm struggling to resolve the issue with super-thin fonts on Safari/iOS despite trying all recommended solutions. Here is the comparison: https://i.stack.imgur.com/5DVHz.png The _document.js file: import Document, { Html, Head, Main, NextScript } fr ...

Avoiding URL images on 404 errors in frontend applications

My goal is to dynamically implement images (from image_url_1.jpg to image_url_5.jpg) based on a specific URL. While everything works fine, I encounter an issue when a particular image, like "image_url_4.jpg," is not available and results in a 404 Error cau ...

Encountering a problem with vis js events

While constructing a timeline in my vue.js application, I opted to utilize vis.js. Unfortunately, I encountered some issues when attempting to incorporate events. Initially, setting @drop="myDropCallback()" did not trigger the function upon dropping an ite ...