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

Connecting Datatables to dynamically loaded tables using Ajax

Currently, I am utilizing bootstrap nav-tabs to load tabs content via ajax. The challenge I am facing involves having two tables within the ajax loaded content that need to be incorporated with the datatable jQuery plugin. I understand that using the &apos ...

Is there a way to specify the dimensions of the canvas in my image editing software based on the user-input

Here is the code and link for my unique image editor. I would like to allow users to enter the desired width and height of the selection area. For example, if a user enters a width of 300 and height of 200, the selection size will adjust accordingly. Addit ...

Finding your site's First Contentful Paint (FCP) can be done by analyzing the

After doing some research on Google insights, I came across information about FCP. However, I'm still unsure about how to determine my site's FCP and other relevant metrics. If anyone could provide me with more information or share detailed link ...

Regular expressions can be used to extract specific attributes and inner content from a div element within a contentEditable container

Context I am currently developing a tagging system called @Name for my website. Successfully, I have managed to detect names upon keystroke and replace the content with the corresponding div class='tag' data-id='User-id'>Name</di ...

Tips for including an external babel JS (ES6) file in an HTML document:

To include the babel js file in an HTML file, take a look at the code snippet below: <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudfl ...

A gap only appears in the drop-down navigation when the page is scrolled

After finally completing my first website, I encountered a frustrating issue. When scrolling down the page, a gap appears in the navigation bar, making it impossible to access the dropdown menus. I've been struggling to fix this problem on my own. Any ...

Is there a way to smoothly navigate back to the top of the page after the fragment identifier causes the page to scroll down?

I do not want to disable the functionality of the fragment identifier. My goal is for the page to automatically scroll back to the top after navigating to a specific section. This inquiry pertains to utilizing jQuery's UI tabs. It is crucial to have ...

Eliminate Element Node Issue

I'm trying to remove a newly generated element using this code, but it doesn't seem to be working. I checked in firebug and there are no JS errors appearing. $('.popular-list li a').on("click",function() { var stuff = $(this).text( ...

Which is better for handling events - jQuery delegation or function method?

Which approach is quicker and has broader browser support? 1. Utilizing a JavaScript function such as: function updateText(newtext) { $('div#id').text(newtext); } and incorporating it into an element's onclick event: <button onc ...

Unforeseen box model quirks found in modern browsers when styling <table> elements

Here is a sample HTML document that demonstrates the issue: <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="Content-Type" content="text/html; ...

Use CSS3 to conceal the form while displaying the default div

In my project, I am restricted to using only HTML5 and CSS3. Currently, I have a form that requires simulating the action of "sending form data". Upon clicking the submit button, the form should be hidden and a default div (#result) needs to be displayed. ...

The process involves transferring information from a specific div element to a database. This particular div element obtains its data after receiving an appended ID

It's a bit complicated, but I'm working on creating a tag system. I'm fetching data from a database with an AJAX call using the "@" symbol. Everything is working fine - the tags are being generated, but I'm having trouble retrieving and ...

Is there a way to remove <font> tags using Javascript designMode?

Currently, I am in the process of developing a WYSIWYG editor as a hobby project. My approach involves utilizing an iframe with design mode enabled and leveraging the execcommand feature in JavaScript to implement the editor functionalities. For instance, ...

Is it possible for jQuery to eliminate script tags that are delivered through AJAX requests?

Upon making an AJAX request in my JavaScript code using jQuery, I noticed that the response includes a <script> tag. However, it appears that jQuery is stripping out this particular tag. Could this be considered typical behavior for jQuery or XHR, o ...

What is the reason behind the submission form functioning properly, while my ajax code is not working as expected?

I have implemented a feature on my chat application where users can print the conversation by clicking a button. The button triggers a PHP script to create a new file, write the conversation to it, and also execute some jQuery code. Using jQuery AJAX fun ...

Strikethrough feature not specified on the website

Check out this unique website that showcases text with a strikethrough. Interestingly, I couldn't find any mention of it in the CSS or HTML code. Here is a snippet from the code: <div style="width:100%;height:259px;background-image: url('< ...

Ways to bypass browser pop-up blockers when using the window.open function

I am displaying an HTML retrieved from the backend. printHtml(htmlContent) { var windowToPrint = window.open('', '_blank'); windowToPrint.document.write(htmlContent); setTimeout(function () { windowToPrint.document ...

Looking for assistance with CSS border animation

Below is my code snippet: .section-one { position: relative; background: #ffffff; } .section-one h2 { color: #000000; font-size: 32px; margin: 0px 0px 10px 0px; padding: 0px; font-family: "AzoSans-Medium"; } ... /* ...

applying conditional rendering in vue.js

I'm currently working on developing a chat application using the guidelines outlined in this tutorial: https://socket.io/get-started/private-messaging-part-1/ One of my goals is to customize the appearance of the messages, so that when a message is s ...

Functionality of multiple sliders

Is there a more efficient way to handle the fading in and out of sections on a slider? I currently have separate functions for each section, but I'd like to simplify it so that I only need one function for all 100 sections. Any suggestions? $(&apos ...