Keeping DIV in place as page scrolls

My webpage has 2 columns, with the left column longer than the right one.

As I scroll down the page, I want the right column to stay fixed in place while only the left column moves.

This will ensure that the right column remains visible at all times regardless of scrolling position.

I initially tried setting the div to position:fixed;, but this caused the right div to overlap the left one.

How can I properly achieve this so that the right div stays in its original position?

Here is a fiddle demonstrating the issue

I also attempted using jQuery to animate the scrolling behavior, but it did not provide the desired result..

$(window).scroll(function(){
  $("#right").stop().animate({"marginTop": ($(window).scrollTop()) + "px", "marginLeft":($(window).scrollLeft()) + "px"}, "slow" );
});

Answer №1

To ensure the #right div stays in place, you must include position: fixed

CSS

#right {
    width: auto;
    float: right;
    top: 40px;
    background-color: #eee;
    border: 1px solid #AAAAAA;
    position: fixed;
}

DEMO

https://jsfiddle.net/wzzopxte/5/

Answer №2

Implementing position:fixed; on the #right_container is effective, however, it is crucial to also specify right:0;

In addition, utilizing percentages instead of fixed widths for the containers enhances responsiveness and prevents div overlap due to position:fixed. However, when fixed widths are necessary, caution should be exercised as there may be unintended consequences.

Refer to the code snippet below and feel free to reach out if you require further assistance:

body {
font-family: arial;
margin: 0px;

.drag {
cursor: move;
margin: auto;
background-color: white;
text-align: center;
font-size: 10pt;
opacity: 0.7;
width: 120px;
min-height: 24px;
line-height: 24px;
border: 2px solid #800000;
}

#drag {
margin: auto;
width: 100%;
display: table;
    position: relative;
border: 1px solid #d9a300;
}

.list {
border: 1px solid #00b359;
min-height: 350px;
    display: table;
width: 100%;
}

#left_container {
width: 63%;
float: left;
margin-right: 2%;
border-bottom: 1px solid #F6F6F6;
border: 1px solid #ff26ff;
    box-sizing:border-box;
}

#left {
width: 100%;
display: table-cell;
border: 1px solid #2d00b3;
}

#right_container {
width: 33%;
float: right;
margin-right: 2%;
border-bottom: 1px solid #F6F6F6;
border: 1px solid #ffff00;
    position:fixed;
    right:0;
}

#right {
width: auto;
float: right;
top: 40px;
background-color: #eee;
border: 1px solid #AAAAAA;
}
<div id="drag">

<fieldset><legend><b>TITLE</legend>
<div class='list'>

<!-- left container -->
<div id="left_container">

<div id="left">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget erat non augue vestibulum fringilla. Maecenas fermentum ante mattis interdum vestibulum.

(Please note that this text has been truncated for brevity) 

</div>

</div><!-- left container -->

<!-- right container -->
<div id="right_container">
<div id="right">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed velit metus, euismod quis ante eleifend, tempor euismod turpis.
</div>
</div>

</div><!--- list --->
    </fieldset>
</div> 

Answer №3

Is this satisfactory? (code updated and explained below)

var right = $("#right_container"); // target the right container element

$(window).scroll(function() {
  right.css("top", $(this).scrollTop()); // change the top position dynamically based on scroll
});
body {
  font-family: arial;
  margin: 0px;
}
.drag {
  cursor: move;
  margin: auto;
  background-color: white;
  text-align: center;
  font-size: 10pt;
  opacity: 0.7;
  width: 120px;
  min-height: 24px;
  line-height: 24px;
  border: 2px solid #800000;
}
#drag {
  margin: auto;
  width: 900px;
  display: table;
  position: relative;
  border: 1px solid #d9a300;
}
.list {
  border: 1px solid #00b359;
  min-height: 350px;
  width: 100%;
  position: relative;
  /* changed to relative positioning */
}
#left_container {
  /* removed float left */
  width: 450px;
  margin-right: 20px;
  border-bottom: 1px solid #F6F6F6;
  border: 1px solid #ff26ff;
}
#left {
  width: 100%;
  display: table-cell;
  border: 1px solid #2d00b3;
}
#right_container {
  position: absolute;
  /* removed float right, used absolute positioning, eliminated margin-right */
  top: 0;
  width: 300px;
  right: 20px;
  border-bottom: 1px solid #F6F6F6;
  border: 1px solid #ffff00;
}
#right {
  width: auto;
  background-color: #eee;
  border: 1px solid #AAAAAA;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="drag">

  <fieldset>
    <legend>TITLE</legend>
<div class='list'>

<!-- left container -->
<div id="left_container">

<div id="left">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget erat non augue vestibulum fringilla. Maecenas fermentum ante mattis interdum vestibulum. Aliquam vel dui ac turpis consectetur accumsan quis eu libero. Sed finibus neque vel ipsum lacinia lobortis. Pellentesque lorem erat, ullamcorper vitae consectetur nec, tempor sit amet nisi. Aenean posuere ante egestas quam rhoncus, ut laoreet dui mattis. Quisque condimentum fermentum metus sit amet posuere. Ut sed lectus orci.
Cras nec enim faucibus, consectetur eros ut, vulputate est. Maecenas sollicitudin vestibulum eros, sit amet porta enim molestie eget. Etiam commodo ex efficitur ligula ornare iaculis. Aliquam erat volutpat. Nullam mollis eleifend nisl a rhoncus. Sed egestas lacinia est ut mollis. Duis fermentum odio eget diam placerat, eu placerat sapien laoreet. Sed mollis leo id tortor dapibus, in finibus lacus aliquet. Donec semper vel libero eu placerat. Nam hendrerit pretium nunc, vel malesuada nisi tincidunt in. Duis ligula metus, dignissim ac laoreet in, aliquam et ipsum. Maecenas non condimentum leo. Morbi convallis turpis lobortis dignissim mattis.
Quisque at hendrerit magna. Praesent id ligula eleifend, semper lacus sed, sagittis mauris. Nulla molestie tristique sem, non ultrices nisl mattis ut. Nulla ut nisi quis elit porta tempor. Duis semper sem tellus, nec viverra metus dignissim nec. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nulla libero lectus, iaculis sit amet enim eget, facilisis blandit enim. Ut dolor massa, imperdiet id lorem a, molestie vestibulum nulla. Fusce non condimentum purus, ut egestas mi. Ut lacinia rutrum nulla a convallis. Vestibulum ac metus urna. In hac habitasse platea dictumst. In ac eleifend mi.
Duis at cursus mauris, non viverra ipsum. Sed facilisis, arcu eu aliquam volutpat, nisi leo interdum neque, in congue libero purus a eros. Pellentesque posuere tellus ut consequat dapibus. Ut dapibus ultrices sem, in posuere eros. Aliquam tincidunt, arcu a dignissim eleifend, urna diam pulvinar urna, non hendrerit lorem urna ac nibh. Cras eu feugiat enim. Aliquam ornare sapien non orci pellentesque, ac pretium felis finibus.
Suspendisse potenti. Cras placerat lorem quis purus facilisis pretium. Ut blandit vehicula erat, eget rutrum elit tempus vitae. Nulla placerat aliquet consequat. Phasellus tempus odio et augue congue venenatis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In gravida, odio vitae porttitor gravida, est elit imperdiet orci, nec pretium lectus risus vitae purus. Aenean dictum nisi a orci aliquet, et scelerisque tortor tincidunt.
</div>

</div><!-- left container -->

<!-- right container -->
<div id="right_container">
<div id="right">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed velit metus, euismod quis ante eleifend, tempor euismod turpis. Suspendisse a euismod nibh, nec viverra ipsum. Sed ullamcorper eros in nisi condimentum rhoncus. Nunc suscipit interdum ligula vel tempus. Donec tortor libero, gravida a condimentum at, lobortis at nibh. Pellentesque habitant.
</div>
</div>

</div><!--- list --->
    </fieldset>
</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

Navigate to a concealed area once the information has been loaded in Angular

I'm working on my very first Angular app, which is a basic weather application. I've encountered an issue where I want to scroll to a specific section after the data has been loaded from the API. This particular section is initially hidden until ...

Ensure that you include validation in the ajax request when loading the message content from a separate file

ajax code for adding data to the database <script type="text/javascript"> $(function() { $(".submit_button").click(function() { var textcontent = $("#content").val(); var dataString = 'content='+ textcontent; if(textcontent=='') ...

Umbraco TinyMCE editor - standard formatting for links

Is there a method within TinyMCE for Umbraco [Version 4.7] to preserve the inline style element of an anchor tag when modified in the editor? In this case, we are unable to utilize CSS since the generated HTML is intended for email clients (inline styles ...

Having trouble retrieving textfield value with jQuery

On my website, I have an invoice.jsp page that requires jQuery to calculate values in textboxes. Within the invoice, there is a quantity textbox. When a user enters a quantity, the price should be dynamically calculated as (total_subPrice= unit_price * qu ...

Infinite loop triggered by jQuery dropdown menu on page resize was causing an issue

I have been working on developing a navigation menu for a website that displays as a horizontal bar on larger screens, but transforms into a jQuery dropdown menu when the window width is less than 980px. During initial page load with a window width below ...

How do you efficiently include several elements within a single column in Boostrap 5?

I've been working with Bootstrap 5 to display a grid of images similar to this link, but the images are not displaying as intended due to some CSS code. #projects img { width: 100%; height: 100%; } <section id="projects"> ...

Automatic capitalization of menu options in Bootstrap dropdown

Is anyone else curious about why the menu items are in all caps while the markup is in lower case? What steps can be taken to prevent this from happening? https://i.stack.imgur.com/S86RO.png ...

The inline style fails to take effect on input elements that are generated dynamically

Consider: $( "#scanInDialogItems tr td:nth-child( 3 )").mouseenter( function() { var q = $( this ).html(); $( this ).html( "<input type='number' style='text-align:right width:50px' min='1' value='" + q + " ...

Tips for placing a fixed footer at the bottom of a container with absolute positioning

I've set up my website container as a white box on a black background, centered on the page to allow for content resizing. Here is the code I used: .container { position: absolute; background-color: white; min-height: 90%; top: 5%; width: 9 ...

The Bootstrap navigation bar fails to expand

After extensive searching, I still can't figure out why my bootstrap menu isn't opening as expected. I made sure to link JQuery first to try to resolve the issue, but it doesn't seem to have made any difference. I'm starting to wonder ...

The AngularJS price slider may exceed its range if the ng-model is null or below the minimum value

I currently have an rz-slider featured on my webpage that is utilized for gathering the price of a product from the user. In addition to the slider, there are two input fields present which are designated for storing the minimum and maximum values. The ng- ...

Encountering an error when utilizing Angular Animation with Bootstrap -> Issue arises from attempting to read properties of undefined (specifically 'box-sizing')

To access the source code of Git, visit https://github.com/codezj/exampleAppAnimation. I recently developed a method to extract Bootstrap CSS and utilize it as CSS in Angular. However, I encountered an error while running the Angular project: Uncaught Typ ...

Performing two consecutive nested AJAX requests in jQuery using JavaScript

I am facing an issue with my code. My goal is to create a cryptocurrency ranking feature on my website. I have integrated an API that provides logos, symbols, indices, prices, etc. of cryptocurrencies. However, I encountered a problem as this API doesn&apo ...

Executing additional code after making an AJAX call in web2py:After firing an AJAX call in

How can I ensure that my code executes after successfully setting options for a second dropdown/select widget using an ajax call in jQuery? view: {{extend 'layout.html'}}` <h1>{{=title}} /This is the library/edit_user.html template</h1& ...

The offcanvas menu in the NextJS Tailwind website does not handle hover or tap events properly when outside of the parent dimensions

My header includes an off-canvas menu that slides in from the right side. Everything seems to be working fine, except for one issue: when the menu is open and visible, the mouse and touch events pass through it to the content underneath. Check out the cod ...

Leverage variables in mixins and extends within Less.js

When using a variable with mixin or extend in Less.js, the following code will result in an error: @bar : bar; .@{bar} { background: yellow; } // ParseError: Missing closing ')' .foo { .@{bar}(); } // This will not work .jam { &:ex ...

Steps for successfully passing an object in a dynamically generated function invocation

In my jQuery script, I have a click event bound to thumbnail images with the class "thumbnail": $(".thumbnail").click(function(){ var obj = new Object(); obj.el = "imageEdit"; obj.id = $(this).attr("id").replace("img_",""); openDialogue(obj); }); ...

Exploring the power of internal linking with GatsbyJS

I am currently developing a website using gatsbyjs. I have concerns about the crawlability of "onClick" for SEO purposes and I would appreciate some assistance. This is my current code: render={data => ( <div className='feed'> ...

Incorporating Ajax content in Struts 2 with the Struts2 Dojo Extension

I'm facing a minor issue with loading content through an Ajax call in Struts 2 (using the Struts2 Dojo Plugin). It's able to load all the HTML content from the page successfully, but it seems to have trouble loading any inline JavaScript function ...

How to toggle the dropdownbox status using jQuery

Just starting with jQuery and I'm looking to enable or disable a dropdown list based on a checkbox. Here's what my html looks like: <select id="dropdown" style="width:200px"> <option value="feedback" name="aft_qst">After Quest&l ...