CSS position fixed. The vertical position of the div wrapper is fixed, while its horizontal position can vary

On my webpage, I have a div with the following CSS styling:

#footer
{   
    position: fixed;
    left: 40px;
    top: 0px; 
}

Currently, the position is fixed both vertically and horizontally when the user scrolls. However, I would like the div to remain fixed when scrolling vertically but to move when scrolling horizontally.

I have searched through various forums and posts, but most solutions involve jQuery scripts. Is there a way to achieve this effect using just CSS?

Fixed position in only one direction I came across this post, but I'm not sure how to implement the jQuery script provided. If possible, please explain how to achieve this effect using CSS, or provide a simpler jQuery solution. Thank you!

Answer №1

It may seem challenging to achieve this desired aesthetic using just CSS and HTML alone. According to insights from Ruup and the discussion on Fixed position in only one direction, incorporating JavaScript for layering could be a viable solution.

Fortunately, I managed to find a workaround that somewhat achieves the desired outcome (albeit not with perfect elegance): http://jsfiddle.net/MKEbW/5/

Within the body tag of the HTML:

<div id="simulated-html">
    <div id="footer">
        <span>
            <!-- Insert footer text here -->
        </span>
    </div>
    <div id="simulated-body">
        <!-- Your website content goes here -->
    </div>
</div>

CSS styling:

* { margin:0; padding:0; }

html {
    font: 12px/1.5em Georgia;
}
p { padding: 5px; }

html, body {
    height: 100%;
    overflow: hidden; /* Conceal scrollbars as custom ones are created */
}

#simulated-html {
    background: orange;
    overflow-x: scroll; /* Show horizontal scrollbars if needed (optional) */
    overflow-y: hidden; /* Hide vertical scrollbars by utilizing #simulated-body */
    position: relative; /* For aligning #footer on #simulated-html */
    height: 100%;
}

#simulated-body {
    overflow-y: scroll; /* Display vertical scrollbars as required (optional) */
    overflow-x: hidden; /* Hide horizontal scrollbars through #simulated-html */
    height: 100%;
    background: #eee;

    /* Acts as a container */
    width: 450px;
    margin: 0 auto;
}

#footer {
    position: absolute;
    bottom: 0px; /* Vertically align with #simulated-html */
    width: 100%;
    background: red;
    z-index: 99; /* Keep footer displayed prominently */
    color: white;
}
#footer span {
    width: 450px;
    margin: 0 auto;
    background: green;
    display: block;
}

​ This solution appears to function effectively across IE7+ and modern browsers, validated via browserlab.adobe.com.

Tests conducted with various scrollbar scenarios, different viewport sizes in Chrome 18.

I recommend having a backup plan for unsupported browsers, or consider implementing a JavaScript alternative if necessary.

Answer №2

If you're looking for a solution, this linked post has exactly what you need. Feel free to copy the script below.

$(window).scroll(function(){
$('#footer').css('left','-'+$(window).scrollLeft());
});

The CSS for the div is as follows (although it might not be for the footer if it's positioned at 0px from the top).

#footer
{  position:fixed;
   left:40px;
   top:0px; 
}

With this jQuery script, the left coordinate of the footer adjusts to match the window's scrollLeft value when scrolling.

Answer №3

We have made a minor adjustment to the code provided earlier.

Here is the updated JavaScript code for horizontally moving a fixed div:

$(window).scroll(function(){
  $('#footer').css('left',-$(window).scrollLeft());
});

Answer №4

What is the best way to adjust the horizontal axis? As it stands, this code keeps the element 40px from the left at all times. To have the left margin change in relation to the window size, percentages and negative margins are necessary. For example, to center a fixed div:

     #centered { 
          height: 350px;
          top: 0;  
          position: fixed;
          width: 1024px; 
          left: 50%; 
          margin-left: -512px; 
          z-index: 9999;
          }

It's important to remember that the negative margin should be half the width of your div. If you want it to be 40px to the left of center, then you would need to add an additional 40px to margin-left.

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

What are some strategies for disregarding global CSS styles?

I am facing an issue on my html page with a specific div structure. The <div id="container">/* lots of nested html with elements like div, ul, li etc */</div> is causing some trouble in my global css file called style.css. The style. ...

Ensure the initial word (or potentially all words) of a statement is in uppercase in Angular 2+

Struggling with capitalizing words in an Angular 2 template (referred to as view) led to an error in the console and the application failing to load, displaying a blank page: Error: Uncaught (in promise): Error: Template parse errors: The pipe 'c ...

Is there a way to include the site_path define('SITE_PATH','http://127.0.0.1/project/'); in a jQuery URL?

Looking for help with my jQuery Ajax code jQuery.ajax({ url:'login.php', }); I am trying to figure out how to add a site path in the url like we define a site path in PHP using define('SITE_PATH','http://127.0.0.1/project/&apos ...

The line numbers are displayed in an unconventional manner next to the textarea

Creating a new text editing tool, here is the code snippet:- const editor = document.querySelector('#ta'); const lc = document.querySelector('#line-count'); var lcDiv = document.createElement('p'); // Function to calculate ...

What is the best way to conceal the blackberry cursor in a web browser?

Is there a way to conceal the blackberry cursor while browsing on the browser? Perhaps through Javascript or CSS? I am attempting to replicate the functionality found in native apps where users can flick through items with their finger. I find this featur ...

When attempting to retrieve JSON data for the second time, AJAX fails to fetch the information

After successfully sending an Ajax request to a php file and receiving a JSON array of the submitted data, I encountered an error on the second attempt. The error message reads: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSO ...

A unique design using Masonry.js featuring a stylish two-column layout showcasing "elevated" blocks of varying sizes

Context I decided to use Masonry.js for this project because I felt it was the most straightforward way to achieve the desired effect, although it might not be the perfect tool for the task at hand. Objective The goal is to create a two-column layout wi ...

What are the techniques for sorting and analyzing objects within an array?

I am working with a JSON structure that needs to be mapped, parsed, and filtered based on a specific attribute value. This process allows me to identify which object contains the desired value so I can access other attributes of the same object and impleme ...

Partial view fails to render correctly through AJAX request

Having trouble with integrating PartialViews and Ajax. My goal is to have a search feature based on category selection and display the result list in a PartialView. The issue I'm facing is that when I click on the search button, it renders the same p ...

What is the best way to toggle the visibility of a background image within a carousel?

As a beginner in j-query, I am struggling with creating a slider image carousel using a full background image. Most of the solutions I found online require a fixed width for all pictures to slide smoothly. However, I believe there might be a way to use an ...

manipulating data using javascript

I have an array of objects like this: var arr = [{'name':'one','age':24},{'name':'two','age':21}] Then I assigned this array to another variable var newVar = arr. Next, I modified the value of a ...

Executing JavaScript code within an AJAX request

Having a problem with an AJAX function that I need help solving: PAGE A represents the main page. PAGE X represents the content loaded via AJAX. RES A represents the results from PAGE A. RES B represents the new results loaded via AJAX. PAGE A initially ...

How can I incorporate random variables and functions into an if-else function when using Jquery to make #divId droppable?

I have most of my code working as I want it to, except for some basic CSS adjustments that need to be made. In a specific part of my code where I am using $("#divId").droppable({over: function(), I want to add 2 other functions and have one of them execute ...

Error: A DATA_CLONE_ERR exception with code 25 was thrown by a web worker

Need help with my web worker: var arrayit = function(obj) { return Array.prototype.slice.call(obj); }; work = arrayit(images); console.log(work); //work = images.push.apply( images, array ); // Method : "load+scroll" var worker = new Worker('jail_w ...

"Enhancing User Experience with Stylish Drop-down Menu Hover

I'm working on a CSS drop-down menu that has a hover effect, but I'm facing an issue where the a element within the li is not taking up the full width of the li. I want it to utilize the entire width of the li, especially on hover. Does anyone ha ...

What is the proper way to document JSDoc in JavaScript specifically for the TypeScript Compiler?

There is a feature that allows you to check JS code with the TS compiler. The TS compiler also recognizes JSDoc comments (https://github.com/Microsoft/TypeScript/wiki/JSDoc-support-in-JavaScript). I am looking to utilize the TS compiler in my React projec ...

Combining AngularJS, Google App Engine (GAE), and Endpoints

I've been working on integrating AngularJS with Google App Engine and endpoints. I have a small testing app with a basic API to help me understand how to use Angular with GAE endpoints. A user inputs text and clicks submit to send the entry to the bac ...

When an AJAX request is made in ASP.NET MVC, it automatically redirects to the login page

In the event that an ajax call is made to retrieve a partial control, but the session has expired or the user is not authenticated, the server will re-render the entire site with the login and master page, along with new CSS, and then send it back to jQuer ...

Tips for keeping a span element from breaking onto a new line in responsive web design

Here is a simple list with h4 headings, each ending with a span element. <ul class="items"> <li> <h4>Avoid Line Break Of Plus <span class="goto">o</span></h4> </li> <li> <h4> ...

Tips for utilizing .html?q= as a hyperlink shortening method

I've been thinking, is there a way to create a simple JavaScript shortening tool where I can manually input the code for JavaScript? Like this: function shortenUrl() { window.location.href = "http://link.com"; } In this code snippet, 12345 repre ...