Strategies for maintaining a sticky element while transitioning between containers

My challenge involves a sticky button located inside a container, but the sticky behavior only seems to work within another element that is full width (container-fluid). Is there any way to make the sticky behavior global?

I have attempted using 'fixed' instead of 'sticky,' but I require the specific behavior that 'sticky' provides. Additionally, I need to maintain the website structure with a container-fluid between containers.

<!DOCTYPE html>
<html>

<head>
  <title></title>
</head>

<body>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <div class="container" style="background-color: green;">
    <div class "row">
      <div class="col-12">
        Lorem ipsum dolor sit amet consectetur adipiscing elit nibh convallis pharetra et fames orci, vestibulum dictum bibendum justo neque metus sem vivamus gravida cursus libero vehicula. Hendrerit ut per risus ac
      </div>
    </div>
    <div class="row sticky-top">
      <div class="col-12">
        <button class="btn btn-primary">Sticky</button>
      </div>
    </div>
    <div class="row">
      <div class="col-12">
        Lorem ipsum dolor sit amet consectetur adipiscing elit nibh convallis pharetra et fames orci, vestibulum dictum bibendum justo neque metus sem vivamus gravida cursus libero vehicula. Hendrerit ut per risus accumsan lacus fames himenaeos orn...
      </div>
    </div>
  </div>

  <div class="container-fluid" style="background-color: yellow;">
    <div class="row">
      <div class="col-12">
        Lorem ipsum dolor sit amet consectetur adipiscing elit nibh convallis pharetra et fames orci, vestibulum dictum bibendum justo neque metus sem vivamus gravida cursus libero vehicula. Hendrerit ut per risus accumsan lacus fames himenaeos orn...
      </div>
    </div>
  </div>

  <div class="container" style="background-color: green;">
    <div class="row">
      <div class="col-12">
        Lore... 
      </div>
    </div>
  </div>
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>

</body>

</html>
@endsection

Answer №1

It is recommended to apply the following properties to the button element instead of the row. Avoid attempting to modify the default classes within a framework, such as trying to apply a `sticky` position to a `row` in Bootstrap - this is not a good practice.

.btn.btn-primary{
    position: fixed;
    top: 0;
    z-index: 1020;
}

Regarding the second question, it is not feasible to alter the behavior of the `container fluid` and `container` classes in the Bootstrap framework, as these are fundamental parent classes that structure elements like `row`, `col`, and `div`. However, you can create your own custom class to achieve the desired outcome.

Answer №2

If you're looking to incorporate JavaScript into your project, the following code snippet may be helpful:

let stick = document.querySelector(".sticky-top");
let fluid = document.querySelector(".container-fluid");

window.addEventListener("scroll", function(){
  let fluidBounds = fluid.getBoundingClientRect();
  let stickHeight = stick.getBoundingClientRect().height;

  if(fluidBounds.y <= stickHeight) {
    stick.style.position = "fixed";
  } else {
    stick.style.position = "sticky";
  }
});

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

Assistance with Php: Need help with remote addresses (I'm a complete beginner in php, apologies)

Hello, I have encountered an issue with some PHP code from OpenCart that is automatically inserting <br /> and commas "," into the addresses of all my customers in the order notification emails. This unintended addition is creating problems with the ...

I am having trouble embedding YouTube videos with my code

Need a fresh pair of eyes on this code. Everything looks correct to me, but it's not functioning as expected. The entries are results from a search. function displayVideos(data) { var feed = data.feed; var entries = feed.entry || []; va ...

When the page is zoomed in, the image exceeds the boundaries of the parent div

I attempted to position the div elements but did not achieve the desired outcome. .tab-vertical { border: 1px solid black; } <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...

Modify FullCalendar: Adjust background color for agendaDay

Although this question has been posed before, the answer remains elusive. I am simply looking for a way to change the background-color of the TD to a specific range. For instance, in my calendar where time slots are structured in 15-minute intervals from ...

PHP script encounters XmlHttpRequest issue when working with a basic task management application

As a newcomer to PHP and ajax XmlHttpRequest calls, I am facing challenges in identifying the issue in my code. Despite reading the documentation, I am finding it difficult to convert the db row names into an array. My goal is to dynamically display an inn ...

When attempting to transfer data to a CSV file from my Firebase database, I encounter an issue where the

I am facing an issue with exporting data from my Firebase Firestore to a .csv file. I have followed all the necessary steps, but whenever I try to add the values for export, they show up as undefined. While I am not an expert in React and consider myself ...

Changing the map behavior when it is moved in Leaflet

I am currently using Leaflet to design a map that includes a personalized sound layer. Each tile on the map features an <audio> element, and I am exploring methods to adjust the audio playback as the user navigates around the map (specifically by mod ...

Using TypeScript, you can pass an object property name as a function argument while ensuring the type is

How can I define a type in a function argument that corresponds to one of the object properties with the same type? For instance, if I have an object: type Article = { name: string; quantity: number; priceNet: number; priceGross: number; }; and I ...

Working with Garber-Irish in Rails: Streamlining Administration and Keeping Code DRY

I am currently implementing the innovative garber-irish technique to organize my JavaScript files. Here's my issue: I have a Model (let's call it Item) with an init function located in app/assets/javascripts/item/item.js For example: MYAPP.ite ...

A guide on incorporating a method using ES6 Rest into a JavaScript object

My goal is to enhance my Person constructor by adding a method that allows users to add friends. I wanted to utilize the "rest" feature of ES6 to pass a variable number of friends, but I seem to be stuck. My initial attempt resulted in an error ("Uncaught ...

Is there a way to display the overall count of items in ReCharts?

I'm curious about how to access the additional data items within the 'payload' field of recharts when using material-ui. Despite my efforts to find relevant sources, I have not come across any references pertaining to accessing other group n ...

Issue with Firefox compatibility in Backbone.js

Greetings! I am currently utilizing Backbone.js and require.js for my application, experiencing difficulty with template rendering in Firefox. Interestingly, it works without issues in both Chrome and IE. Allow me to present the code responsible for rende ...

Preserve jQuery-enhanced webpage changes permanently

I am looking to permanently save modifications made on an HTML page using JQuery. I have come across suggestions about achieving this by sending an Ajax call and storing the data in a database table. However, I am unsure about what exactly needs to be save ...

When incorporating Routes into App, it is important to note that React does not accept functions as valid children

I am currently working on wrapping Routes using a Layout component to organize all content within a bootstrap 12 column grid. However, I am facing an issue where my text inside Route components is not being wrapped and I receive a warning stating that func ...

Exploring the Content Returned by AJAX

Recently, I've been working on an AJAX request that dynamically populates content on my HTML page. However, I encountered a challenge when trying to access an anchor tag in the AJAX response using its ID to display an alert. Here is the snippet of my ...

Clicking on the title link will open the content in an iframe, but the image

Having trouble with a previous post but I've created a codepen to illustrate the issue. Hoping someone can help me out! Check out the codepen here: "https://codepen.io/Lossmann/pen/GRrXyQY" ...

Why does my contact form display PHP code unexpectedly?

I've been following a YouTube tutorial to create a responsive single-page website using Bootstrap. The tutorial covered the front-end, but now I'm stuck on integrating a contact form. I added some PHP code I found online, but there seems to be an ...

The bar chart in chartjs is not displaying properly due to incorrect grouping

I attempted to generate a multi bar chart using Chart.js, but encountered an issue where the jobType and jobCount were not displayed correctly based on each companyName. Below is the table: https://i.sstatic.net/ZyKZH.png Here is the PHP file (CompanySel ...

The error message "Error: 'x' is not a defined function or its output is not iterable"

While experimenting, I accidentally discovered that the following code snippet causes an error in V8 (Chrome, Node.js, etc): for (let val of Symbol()) { /*...*/ } TypeError: Symbol is not a function or its return value is not iterable I also found out ...

Is it possible to modify variables in the controller when the route is changed?

My application utilizes a template and several views that are dynamically rendered based on their route: popApp.controller('HomeCtrl', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http) { ...