Locked element within a restricted container

I've been searching for a solution to this issue for hours, but it seems that others' problems were simpler than mine.

Is there a way to keep a position:fixed element inside a fixed-sized div without it overflowing?

In simpler terms, I want scrollbars to appear in the div if the fixed element grows, while keeping the element fixed when scrolling vertically (I plan to use JQuery for this).

Thank you in advance.

<style> 
    .container {
        width:200px;
        height:200px;
        border:solid 1px black;
        overflow:scroll;
    }       
    .fixed-element {
        position: fixed;
        width:250px;
        height:100px;
        background-color:red;
        top:10px;       
    }
    p {
        min-width: 300px;
    }
</style>
<body>  
    <div class="container">
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
        </p>
        <div class="fixed-element">         
        </div>
    </div>  
</body>

EDIT: I'm aiming for a similar effect as the middle box on this page: , but within a scrollable div instead of the entire viewport.

Answer №1

I have come up with a solution to address your problem. However, there is an issue where you cannot scroll when hovering over the fixed (red) box.

It's uncertain how critical this limitation may be.

To resolve this, I introduced another element called .holder and adjusted the positioning of your fixed element using position: absolute; to ensure it remains within the .container.

.container {
  position: relative;
  width:200px;
  height:200px;
  border:solid 1px black;
  overflow: hidden;
}       
.fixed {
  position: absolute;
  width: 250px;
  height: 100px;
  max-width: 175px;
  background-color: rgba(255,0,0,0.5);
  top: 10px;
  left: 10px;
}
.holder {
  width: inherit;
  height: inherit;
  overflow:scroll;
}
p {
  min-width: 300px;
}
<div class="container">
  <div class="fixed">
This is "fixed"
  </div>
  <div class="holder">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>
  </div>
</div>


Edit

To resolve the issue of the red box overlapping with the scrollbars, consider adding a max-width property to your .fixed element, as showcased in the snippet below.

If determining the exact width of the scrollbar across different browsers is necessary, JavaScript will be required. For guidance on achieving this, refer to the discussions on stackoverflow and davidwalsh-blog linked here and here.

Answer №2

The position: fixed CSS property is used to specify an element's position in relation to the page. It is important to set the parent div as fixed and the child div as relative.

HTML

<div class="parent">
    <div class="child"> ... </div>
</div>

CSS

.parent{
    position: fixed;
    height: 100px;
    overflow-y: scroll;
}

Live Demo

Check out the live demo here!

Answer №3

position: fixed only applies to the viewport, meaning you cannot make an element stick in place relative to its parent. Instead, use position: absolute to achieve a similar effect to fixed.

You can see this in action in this example on JSFiddle.

If you want to create a "pseudo" fixed positioning for elements within their parents, you can enclose both the parent and the desired fixed element in another container.

To prevent your text from wrapping, utilize the white-space property with a value of nowrap; if you need a scroll bar, add overflow: scroll to the element.

Check out the behavior demonstrated here on JSFiddle or in the code snippet below.

html, body {
    margin: 0;
    padding: 0;
}

.wrap {
    background-color:#ccc;
    position: relative;
}

.a {
    height: 150px;
    overflow-y: scroll;
}

.b {
    margin-top: 300px;
    padding-bottom: 20px;
}

.footer{
    position:absolute;
    bottom:0;
    left:0;
    background-color:#666;
    color:#fff;
    width: 100%;
    white-space: nowrap;
    overflow: scroll;
    padding: 10px 0;
}
<div class="wrap">
    <div class="a">
        top
        <div class="b">bottom</div>
    </div>
    <div class="footer">Some text Some text Some text Some text Some text Some text AAA text Some text Some text AAAA text Some text Some text Some text Some text Some text Some text </div>
</div>

Answer №4

After considering various options, I decided to tackle the issue from a different angle by relocating the .fixed-element outside of the .container and adjusting its width to match that of the container. I then enclosed it in its own div with overflow set to hidden. To synchronize the scrolling of both the .fixed-element div and the .container, I utilized JQuery. Grateful for the assistance provided by everyone.

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

Using jQuery for real time countdown and count up synchronization with server-side values

Script: Every day, I receive a json response with specific event timings: items: { fajr: '5:23 am', sharooq: '7:23 am', dhur: '1:34 pm', asr: '4:66 pm': magrib: '6:23 pm', isha: '8:01 pm'} Upon ...

Delete all offspring nodes from the Google organization chart

I am currently utilizing the Google Organization Chart to create a chart that resembles the attached screenshot. There is a specific method called removeRow(nodeIndex) that I am using to eliminate a node from the chart. However, one issue I faced is that ...

A div element springs forth into a new window and seamlessly transitions back to its original position with fresh content

Most of us are familiar with Gmail chat, where you can pop out the chat window into a new window with its content, and then pop it back in to its original position. However, I encountered an issue while working on replicating this functionality. While I w ...

Jquery-Tools Tabs AJAX Caching: almost within reach but slightly out of grasp

Wow, JqueryTools Tabs is truly impressive [http://flowplayer.org/tools/demos/tabs/ajax.html]. However, the downside is that these tabs with AJAX functionality do not cache. This means a fresh reload every time you click on a tab. We're getting closer ...

Is there a way to switch between showing and hiding all images rather than just hiding them one by one?

Is there a way I can modify my code to create a button that toggles between hiding and showing all images (under the user_upload class), instead of just hiding them? function hidei(id) { $('.user_upload').toggle(); Any suggestions would be grea ...

adding a variable to the value of an input field using the val() method

Here is a code snippet that appends the text 'text goes here' to an input value: $('#someid').val($('#someid').val() + 'text goes here'); I attempted to use a variable in a similar way, but it didn't work as e ...

Unable to submit form using jQuery is not functioning as expected

I am attempting to trigger a function when the submit button in the form is clicked. My aim is for the page not to refresh, and instead, I want to use AJAX to add the category. The issue arises when I manually include it in the HTML file, everything works ...

Is there a way for me to execute a function multiple times in a continuous manner?

I am attempting to create a blinking box by calling a function within itself. The function I have is as follows: $(document).ready(function(){ $("button").click(function(){ $("#div1").fadeToggle("slow"); }); }); <script src="https://a ...

"An unanticipated parameter was encountered while using jQuery AJAX to make

I have a specific request: bindAutoComplete('pro_title'); This command triggers the usage of a jQuery AJAX call within this function: function bindAutoComplete(id) { $("#" + id).keyup(function() { if (this.value.length > 1) { ...

Transform the Bootstrap container to fill the entire height of the browser

How can I make the container height 100% of the browser without breaking the contents inside? html, body { height: 100%; min-height: 100%; } .container { min-height: 100%; height: 100%; background-color:red; } <div class="contai ...

Toggle the visibility of a div based on whether or not certain fields have been filled

Having a form with a repeater field... <table class="dokan-table"> <tfoot> <tr> <th colspan="3"> <?php $file = [ 'file' => ...

Plotting jQuery Flot Graphs Over Background Images: A Step-by-Step Guide

Is there a way to overlay a graph on top of a background image? I've attempted various methods with no success. Frustrating! ;) The code snippet below only displays the image, not the graph. Could it be because the graph is plotted behind the image? ...

My preference is for the flex box to expand in width (sideways) without increasing in height (up and down)

Is there a way for flex items to expand in width but only in height when necessary? I enjoy using flexbox, but I find it frustrating that all flex items in a row grow to the same height even when there isn't enough content to fill them, resulting in a ...

JavaFX GridPane: Automatically adjust size when content is hidden or disabled

Is it feasible to reduce the size of a GridPane row if the content in that row is both disabled and invisible? Even when a Node is set to disable=true and visible=false, the cell continues to occupy space. If I have 8 rows but only the first and last are ...

Crafting callback functions

My jQuery code looks like this: $('#current_image').fadeOut(function(){ $('#current_image').attr('src',newImage).show(); }); This process is wonderful - the nested function runs smoothly after the fadeOut. I ...

How can I customize my navigation bar to resemble the design in the image?

I have been struggling to recreate a navigation bar that matches the design in the image provided below. Despite my efforts, I have only managed to come up with the code below. The method I used was inspired by a solution found on Stack Overflow, but I am ...

How can I position a Button at the center of my Grid item using Material UI?

In my React 16.13.0 application, I am utilizing Material UI's Grid and trying to center the content of a button in the middle of a row. Here is what I have tried: center: { alignItems: "center", width: "100%", }, halfRow: { width: "5 ...

How can parameters be passed to a named function from a controller in AngularJS?

In my controller, I am working on breaking up my code into named functions to make it more readable. However, I am facing an issue where the scope and injected dependency are null in the parameterized named functions. How can I access these inside the name ...

Tips for populating two drop-down menus within a row that is created dynamically

Issue: I'm unable to populate drop down lists in dynamically generated new rows. $('#Title_ID option').clone().appendTo('#NewTitle_ID'); $('#Stuff_ID option').clone().appendTo('#NewStuff_ID'); These lines handl ...

Advancing past the stage of developing basic functions in the document.ready() event handler

When I develop a website, I have a personal preference of creating a main JavaScript file with window.load and window.ready functions at the top. I find it easier to refactor any logic into separate functions within these functions for better readability. ...