Positioning a div relative to another div using the pos:fixed attribute

Is there a way to make a fixed position div relative to its parent div instead of the window using only CSS? I want a sticky block that follows the content while scrolling with the page, and stays in place even when the window is resized.

I know this can be easily achieved using JavaScript, as shown in the example code below:

function sticky() {
    $('.sticky').css({ //sticky block
        left : $('.container').offset().left + parseInt($('.container').css('width'))
    });
}

sticky();

$(window).resize(function() {
    sticky();
});

However, I'm concerned about performance issues on the page if relying on JS. Is there a pure CSS solution for achieving the same functionality?

Check out the JSFiddle demonstration here: http://jsfiddle.net/zcqbsrzf/

Answer №1

Introducing a new CSS property:

position:sticky

Note that Browser support is currently limited to Firefox and Safari

FIDDLE (For Firefox and Safari)

Despite setting top:0;, the sticky div may not appear at the top of the viewport as expected

.container {
  width: 400px;
  height: 5000px;
  background: gray;
  position: relative;
  color: #fff;
  margin-top: 50px;
}
.sticky {
  width: 100px;
  height: 100px;
  margin-right: -100px;
  float: right;
  position: -webkit-sticky;
  position: sticky; /* <---- */
  background: green;
  color: #fff;
  top: 0;
}
<div class="container">container
  <div class="sticky">sticky
  </div>
</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

How do I create a notification when the div reaches 100% alignment on the left side using Javascript?

Is there a way to receive an alert when the div with the class name "earth" reaches 100% on the left side, without using jQuery? I attempted to utilize setTimeout but I am looking for an alternative method that does not rely on time, but rather on positi ...

Having difficulty transmitting extensive data in a Jquery ajax request

Hello, I'm currently working on a MVC4 application where I am saving values to a Database. However, I encountered an error stating: "The request filtering module is configured to deny a request where the query string is too long." I am using an Ajax ...

The function of JQuery .click() is successful when used on a local machine, however it is not functioning

I am facing a puzzling issue. The code in question functions perfectly on my local server, but once I uploaded it to my hostgator server, a specific function no longer executes. When I set a breakpoint in the Firefox debugger, I noticed that the function i ...

Refresh only a portion of a page using PHP and JavaScript

I have a webpage set up with multiple sections in separate divs. Currently, the essential divs required are <div id="main">...</div> & <div id="sidebar">...</div> Each div contains PHP code like: <?php include("page.php") ...

Samsung mini devices experiencing issues displaying Unicode symbol (25be)

I'm currently facing an issue with an iconfont that I have included in my website. I am using Unicode symbols for the characters of the icons, and most of them are displaying correctly. However, there are a couple that are showing up as blank on the s ...

Switching the theme color from drab grey to vibrant blue

How can I change the default placeholder color in md-input-container from grey to Material Blue? I have followed the instructions in the documentation and created my own theme, but none of the code snippets seems to work. What am I doing wrong? mainApp. ...

Achieving dynamic text alignment within a Grid tile container using HTML and Angular

Here is the main section of my parent component. <div class="o-tile-container "> <div *ngFor="let country of Countrys"> <app-country [na ...

Attempting to utilize ajax in Laravel, however encountering a 404 error

Trying to retrieve data through JSON using AJAX. Controller: public function getFreeDay(Reservation $reservation): JsonResponse { //other data will be here, this is just for testing try { return response()->json([ 'stat ...

Enigmatic void found beneath image surfacing

Similar Question: Dealing with Additional Space at the Bottom of an Anchor Tag Take a look at this example page here.. There seems to be a mysterious gap below the picture of the family, just before the gray-bordered (5px #333) div that holds the ima ...

Adding an element to the second-to-last position in a list

In the context of a HTML unordered list <ul id = "master_key_list"> <li id="master_key_23" class="available_element">Fix the Peanut Butter</li> <li id="master_key_24" class="available_element">Focus on Price Sensitivity</li& ...

What is the purpose of adding data to the end of a URL?

There are two primary methods for appending data to a URL, although there may be additional ways. Using the Http get method With the help of .serialize() function Both of these methods involve adding data to the URL, typically in connection with forms. ...

What is the correct CSS2 selector syntax to apply the :hover effect to the nth child of a specific element?

My goal is to apply a unique background color to each menu li element when hovered over, and I want to accomplish this using CSS2. <ul> <li> <li> <li> <li> </ul> I managed to add a background color to t ...

How can I insert a zero value in front of single digit hours in Timepicker using Jquery?

My timepicker is set up like this: $('#datepickerTime').timepicker({ timeFormat : "hh:mm:ss" }); However, the issue arises when the time is between 1 and 9 because it does not automatically add a leading zero (e.g. 01:30). How can I make su ...

It appears that the jQuery script is not loading properly

For my wordpress site, I have integrated jQuery using the wp_enqueue_script function along with the jQZoom script. In the header of my site, you can find the following lines in this order: <link rel='stylesheet' id='jQZoom_style-css&apo ...

Preventing Cross-Site Scripting (XSS) when injecting data into a div

I am using Ajax to fetch data in JSON format and then parsing it into a template. Here is an example of the function: function noteTemplate(obj) { var date = obj.created_at.split(/[- :]/), dateTime = date[2] + '.' + date[1] + '. ...

Show Zeroes in Front of Input Numbers

I am working with two input fields that represent hours and minutes separately. <input type="number" min="0" max="24" step="1" value="00" class="hours"> <input type="number" min="0" max="0.60" step="0.01" value="00" class="minutes"> This se ...

jQuery doesn't have the capability to convert this data into JSON format

I have some code that I want to convert into JSON format: var locationData = []; locationData['lat'] = position.coords.latitude; locationData['long'] = position.coords.longitude; locationData['address']['road'] = da ...

What are the steps for creating an animated visualization of the peak chart?

As a newcomer to CSS and Javascript, I am currently struggling with animating a peak (bar) chart that I came across on codepen. If anyone can provide assistance or guidance, it would be greatly appreciated! The chart can be found here: http://codepen.io/An ...

Leveraging the power of LARAVEL with AJAX by implementing a customized

As a newcomer to Laravel and Ajax, I've encountered an issue. When running the following script: $.ajax({ type : 'GET', url : 'getListeGenreCategorieAjax/'+$(this).val() , dataType : 'html', ...

Modifying the font style within an ePub document can affect the page count displayed in a UIWebView

Currently in the development phase of my epubReader app. Utilizing CSS to customize the font style within UIWebView, however encountering a challenge with the fixed font size causing fluctuations in the number of pages when changing the font style. Seeki ...