The div's width shifts upon reaching the top of the page

Creating a blog site example and trying to lock the position of a div once it reaches the top of the page. Utilizing materialize.css for this task.

<div class="row">
     <div class="col m8 s12">
     <!-- content goes here -->
     </div>

    <div class="col s12 m4">
                    <div class="collection with-header" style="margin-top:3rem;">
                        <h5 class="collection-item">Trending topics</h5>
                        <a href="#" class="collection-item">Web design</a>
                        <a href="#" class="collection-item">Express framework</a>
                        <a href="#" class="collection-item">Cache API</a>
                        <a href="#" class="collection-item">Event handling in JavaScript</a>
                        <a href="#" class="collection-item">Django framework</a>
                    </div>

    <!-- This div should be fixed after reaching the top -->
                    <div class="card-panel center" id="post-author" style="width:auto">
                        <div class="follow-author">
                            <img src="https://source.unsplash.com/random/200x200" alt="" class="responsive-img circle"
                                style="width:75px;">
                            <div class="blue-text darken-3">Ishaan Sheikh</div>
                            <small class="grey-text">@sheikh_i</small>
                            <div class="divider" style="margin:1rem 0;"></div>
                            <div class="grey-text">Follow Author </div>
                            <a href="#"><i class="fab fa-facebook"></i></a>
                            <a href="#"><i class="fab fa-twitter"></i></a>
                            <a href="#"><i class="fab fa-instagram"></i></a>
                            <a href="#"><i class="fab fa-github"></i></a>
                         </div>
                    </div>
     </div>
 </div>

Javascript code:

window.onscroll = function () {
            myFunction();
        };

        var header = document.getElementById("post-author");
        var sticky = header.offsetTop;

        function myFunction() {
            if (window.pageYOffset > sticky) {
                header.classList.add("sticky");
            } else {
                header.classList.remove("sticky");
            }
        }

The sticky class definition:

.sticky {
            position: fixed;
            top: 0;
        }

The issue encountered is that the fixed div width changes and shrinks unexpectedly. Seeking a solution for this problem which has been ongoing for the past couple of days.

Example can be viewed Here

Answer №1

The issue lies in the inclusion of the sticky class that includes the position: fixed; property.

By using fixed, the div is taken out of the column, causing width:auto to function differently than expected.

To resolve this problem, consider restructuring the columns with specific fixed widths.

UPDATE

Fixed Positioning

When an element's position is set to fixed, it is removed from the normal document flow and no space is reserved for it in the layout. It is positioned relative to the initial containing block determined by the viewport, unless there is an ancestor with properties like transform, perspective, or filter applied. In such cases, the ancestor becomes the containing block. Note that browser inconsistencies may arise with perspective and filter impacting containing block formation. The final position of the element is defined by top, right, bottom, and left values. Elements with fixed positioning always create a new stacking context and retain the same position on each page when printed.

Find more information about CSS position here

Answer №2

When using the CSS property <strong>position:fixed</strong>, keep in mind that it removes the element from the normal flow of the document, causing its width to automatically adjust. To maintain a consistent width, specify a fixed width for the element like this:

.sticky {
  position: fixed;
  top: 0;
  width: 321px;
}

To learn more about CSS positioning properties, visit https://css-tricks.com/almanac/properties/p/position/

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

Executing jQuery post request on a div loaded via ajax

I'm facing a challenge with my webpage. I have a section where the content of a div is loaded via ajax. This div contains forms, and after submission, it should update to display the new content without refreshing the entire page. Can anyone guide me ...

Leveraging HTML Page Variables in Google Tag Manager for Enhanced Merchant Code Integration

I'm currently in the process of incorporating Google Merchant Code via GTM on a product checkout/thank you page. The Google Merchant code is : <script> window.renderOptIn = function() { window.gapi.load('surveyoptin', function() { ...

Is it possible to display this code through printing rather than using an onclick event?

I have a puzzle website in the works where users select a puzzle to solve. I am looking for a way to display the puzzles directly on the website instead of using pop-up boxes. I am proficient in various coding languages, so any solution will work for me. ...

Interactive Dropdown Menu Generation

Despite my expertise in programming languages like MySQL, PHP, JavaScript, jQuery, HTML, and CSS, the current issue I am facing does not relate to any of these. It essentially comes down to three key aspects: Creating a menu layout with clickable link op ...

What causes my image to overlap my navigation bar when I rotate it?

Is there a way to rotate images in CSS without causing them to overlap with other elements on the page? When I try to adjust the rotation property, the image sticks to the top of the page and overlaps the navigation bar. Below is the code snippet: HTML C ...

Generating CSV headers for all nested objects in JavaScript

Utilizing the "react-json-to-csv" library to convert my JSON data into a CSV file has presented an issue with nested objects. The CSV export header is breaking, displaying alternate data because of these nested objects. Here's an example of my JSON da ...

Attempting to remove certain characters from a given string

let currentDate = new Date(); currentDate.toLocaleString; If I were to console log the value of currentDate, it would show: Wed Oct 16 2019 15:57:22 GMT+0300 (Israel Daylight Time) However, what if I only want to display the minutes and seconds like 57: ...

How can I specify the array's length when using JSON.stringify in AngularJS?

I am looking to store form values in JSON to send via $http.post. One of the values, rooms, should be an array with a length determined by the selected value from md-select. The value of Adult should be included within each room entry. var data = { rooms: ...

Tips for managing a stored data reservoir with react-query

I am looking to develop a unique custom hook that can effectively manage a cache and fetch only new items. Here is the expected behavior: Upon initial request for [1, 2, 3, 4, 5], it should fetch all [1, 2, 3, 4, 5] as the cache is empty. If a request is ...

How to retrieve the selected text from a specific <span> using JavaScript

Is there a way to extract only the selected text from a specific span element? <span style="font-size:40px">Hi tTheee</span> <span style="font-size:20px">hello</span> <span style="font-size:20px">sdsds </span> Current ...

Utilizing SlickGrid and DataView for calculating totals efficiently without the need for grouping

I am attempting to utilize Slick Grid and DataView to calculate column totals similar to the example shown here: . However, I do not want to group my rows. Therefore, I attempted not passing a getter and formatter into the dataView.setGrouping(..) method. ...

Different perspectives displayed simultaneously on a single page, achieved without the need for routes

On my page, users have the ability to sort items using various filters. When the filter is set to Newest, the items are simply listed by name. But when the filter is set to By collection, the items within a specific collection are displayed under that col ...

Leveraging JavaScript Functions in HTML

I am having an issue with a JavaScript file containing two similar functions that are executed through an HTML form. While the first function runs smoothly, the second function does not display correctly. It seems like I might be calling or executing the ...

Assign a value to an element based on a specific attribute value

I'm working with the following element <input type="text" size="4" name="nightly" value="-1"> My goal is to update the value to 15.9 specifically when name="nightly" Here's what I've attempted so far: document.getElementsByName(&ap ...

Passing variables dynamically in a created Express.js route

Creating routes in Express.js from a JSON file with the specified structure: { "/home":{ "token":"ksdjfglkas" }, "/logout":{ "token":"ksdjfglksaudhf" } } It is necessary to access the token within the routes function. The JavaScript code ...

What is the best way to transfer data from a database query to Vue?

I am currently working on an API request that involves calling a SQL query within the function. I want to pass the results to a .vue page utilizing express-vue. Below is the code snippet for the API request: router.get('/search', (req, res, next ...

Receiving an empty response while attempting a cross-domain AJAX request using YQL

I have implemented the code below for performing a cross-domain AJAX request using YQL : function requestCrossDomain( site, callback ) { function cbFunc(data) { // Proceed if there is data to work with... alert("inside call back"); if ( data.results[0] ...

What is the best way to insert text into a paragraph tag using JQuery?

As part of my learning journey on Codecademy, I decided to challenge myself by creating my very first Chrome extension using HTML/CSS, jQuery, and Javascript. My initial goal is to learn how to append text to a paragraph tag when a button is clicked. Here ...

Rearrange the position of an element within an array

I'm struggling to find a solution for rearranging elements within an array. Consider the following: var array = [ 'a', 'b', 'c', 'd', 'e']; How can I create a function that moves the element 'd&a ...

Displaying a different background color on a colgroup element in CSS when a scroll is

My webpage contains one or more large and complex tables, where I use JQuery to add background-color to tr and colgroup elements when hovering over the table(s). An issue arises when there are multiple tables on a page that extends beyond the viewport wit ...