Trouble with setting the width of a fixed element within a parent div

My goal is to make an element's position fixed and have it take up the full width of its parent div. Below is the HTML I am working with:

     <div class="col-md-3">
        <div class="player-avatar-card">
          <div class="card-body">
            <div class="avatar-image">
              <img src="/imagecache/small/{{ $player->image_filename }}" alt="Profile Image" class="rounded-circle">
              <img class="flag rounded-circle" src="/icons/flags-round/{{ $player->nationality }}.svg"></h3>
            </div>
            <h5>{{ $player->first_name }} {{ $player->last_name }}</h5>
            <p>{{ $player->nationality }}, {{ $player->age }} years</p>
            <div class="social-buttons">
              <div class="col-12">
                <a class="btn btn-info btn-lg" href="#" role="button">
                  <i class="ion-plus-round"></i> follow</a>
              </div>
              <div class="col-12">
                <a class="btn btn-info btn-outline-info" href="#" role="button">
                  <i class="ion-android-share-alt"></i> share</a>
              </div>
            </div>
          </div>
        </div>
      </div>

I am applying a fix position class, is-fixed-avatar, when scrolling to the element:

  const avatarCard = document.querySelector('.player-avatar-card');
  const fixClassAvatar = 'is-fixed-avatar';

  function stickyScroll() {
    if( window.pageYOffset > 56 ) {
      avatarCard.classList.add(fixClassAvatar);
    }
    if( window.pageYOffset < 56 ) {
      avatarCard.classList.remove(fixClassAvatar);
    }
  }
  $(window).scroll(stickyScroll);

Here is the CSS class being applied:

.is-fixed-avatar {
  position: fixed;
  max-width: inherit;
  width: 100%;
}

However, the element extends outside of the col-md-3 div. How can I resolve this issue?

View the fiddle here. Be sure to expand it on the screen for better visibility.

Answer №1

When you apply position: fixed, the div is removed from the flow and therefore detached from the col-md-3 container. My suggestion is to switch it to absolute:

.profile-content .player-info .is-fixed-avatar {
  position: absolute;
  left: 0;
  right: 0;
}

You can now use jQuery to add some level of "stickiness" to the avatar - test this behavior by adjusting the window height. Refer to the simplified demo below (the last section-card is nested inside the col-md-9):

$(document).ready(function() {
  const avatar = $('.player-avatar-card');
  const avatarBox = avatar.parent();

  function sticky() {
    var offset = avatarBox.offset().top - $(window).scrollTop();
    if (offset >= 0) {
      avatar.css('top', '0');
      return;
    }
    avatar.offset({
      'left': avatar.offset().left,
      'top': -offset + 90 // Adjusting for padding with 90px
    });
  }
  $(window).scroll(sticky);
});
// CSS Styles

/* Additional styles go here */
.is-fixed {
  /* fixed positioning styles */
}

.page-nav {
  /* Page navigation styles */
}

.lg-strong-font {
  /* Large font styles */
}

.profile-content {
  /* Profile content styles */
}

// More CSS styles...

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

<div class="container-fluid page-nav">
  <div class="container">
    <div class="row">
      <div class="col-md-9 offset-md-3">
        <nav id="page-nav" class="nav section-links">
          <a class="nav-link active" href="#info">Info</a>
          <a class="nav-link" href="#videos">Videos</a>
          <a class="nav-link" href="#stats">Statistics</a>
        </nav>
      </div>
    </div>
  </div>
</div>
<div class="profile-content">
  <div class="row player-info">
    <div class="container">
      <!-- Content structure goes here -->
    </div>
  </div>
</div>

Answer №2

In order to accomplish your desired outcome, there are three different approaches you can take.

Method 1

To start, you can enclose the fixed element and the scrollable content within a parent element. Set both elements to have a position: absolute property and apply overflow: scroll specifically to the content element. When implemented correctly, the fixed element will not move as the parent element does not scroll.

CSS

.parent {
    position: relative;
    width: 800px;
    height: 400px;
    overflow: hidden; // To prevent unnecessary scroll bars
}
.fixed-menu {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 20px;
    z-index: 2;
}
.content {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    overflow-y: auto;
}

HTML

<div class="parent">
    <div class="fixed-menu"></div>
    <div class="content"></div>
</div>

Method 2

An alternative method is to create a child that is absolutely positioned, followed by a grandchild containing the fixed content. By omitting specific positioning attributes for the fixed grandchild, it will remain fixed relative to the child's position.

.parent {
    position: relative;
    width: 25%;
    height: 200px;
    overflow: scroll;
    background-color: #f0f0f0;
}

.child {
    position: absolute;
    width: 50px;
    height: 50px;
    top: 50px;
    right: 50px;
}

.grandchild {
    width: 50px;
    height: 50px;
    position: fixed;
    background-color: red;
}

HTML

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

Method 3... Kind of

The third approach involves establishing local coordinates for child elements by utilizing either will-change: transform or transform: translate*(0). This creates a separate rendering layer for the element with its own coordinate system.

CSS

.parent {
    position: relative;
    width: 30%;
    height: 200px;
    overflow: scroll;
    background-color: #f0f0f0;
    transform: translateX(0); // Choose any axis for transformation
}

.child {
    position: fixed;
    width: 50px;
    height: 50px;
    top: 25px;
    right: 25px;
    background-color: red;
}

HTML

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

I'm currently exploring the third method further as it seems to behave differently than what I anticipated. The observed glitch in modern browsers where the fixed element acts similarly to an absolute element suggests there may be a potential workaround, but additional experimentation is required to validate this assumption.

Wrap Up

You now have multiple methods at your disposal, each offering a unique way to achieve your goal. My focus remains on refining the third method due to its intriguing behavior, opening up new possibilities for achieving the desired outcome through experimental adjustments.

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

Styles for reading on Safari using an iPhone's reader mode

Currently in the process of optimizing my website for iPhones and exploring the Safari reader function. I believe it's a useful feature for websites with lengthy text, similar to mine, but I want to customize it slightly. Is there a way to adjust th ...

The website on iPad automatically zooms in upon opening and then increases the zoom level even further when a specific button is tapped

I recently coded a website using html, css, and js. It seems to work perfectly on all devices except for the iPad. Interestingly, when I use the iPad emulator in Google Chrome, everything appears normal. However, when I open the website on an actual iPad, ...

JSON Compression/Decompression Utility

Looking for a solution to handle large data sets in a .NET Web Method (C#) that accepts JSON objects generated by JQuery on the client side using Ajax. The current process is functional, but there is concern about handling potentially very large amounts o ...

Modify the state of each individual button

I recently came across a cool implementation using clicks and jQuery fade effects to show a div when a button is clicked and then change the state of the button. Check it out here: http://jsfiddle.net/ttj9J/5/ HTML <a class="link" href="#" data-rel="c ...

PHP data grid selects a field and dynamically generates a dropdown menu from other tables

I'm currently using phpMyDataGrid and I'm having trouble implementing a dropdown list menu in one of the columns. $objGrid = new datagrid; $objGrid->closeTags(true); $objGrid->friendlyHTML(); $objGrid->methodForm("get"); $objGr ...

Filter input in jQuery for a textarea box

I implemented a modification of this technique in my code. The main purpose is to prevent unauthorized characters from being entered by the user (there is also a filter on the server side). $('#someinput').keyup(function() { var $th = $(this ...

How to align text to the right in a Bootstrap 5 card header

I'm facing an issue with a Bootstrap 5 card where I want to align certain content in the header to the right and some to the left. Despite my efforts, everything remains left-aligned. Here's a snippet of my code: <div class="card"& ...

Tips on choosing a button and applying custom styles with emotion styles in MUI

Looking to apply a margin-right to my button. Currently utilizing mui 5 with Button variant='contained'. I created a custom CSS style using the styled component in mui and targeted the Box. const Wrapper = styled(Box)({ display: 'flex&ap ...

The javascript code appears to be functioning properly on desktop browsers but is not functioning as expected on Chrome's mobile browser

On my WordPress site, I have created a Java Bootstrap loan calculator that works perfectly on desktop. However, when I use Chrome on mobile, it is not functioning properly. I tried using the wp-coder plugin and also manually added the necessary code. Int ...

Using jQuery to automatically scroll to the bottom of a div when sliding down

When a user clicks on a link to slide the div down, I want it to automatically scroll to the bottom of the div. I've attempted to use scrollTo and animate methods to achieve this effect. $('html, body').animate({ scrollTop: $("#elementID") ...

Why does CodeIgniter consistently return true when using Jquery's .ajax() and form validation?

I am facing a confusing issue with the codeigniter form validator. Despite entering the value 'test' into the alias element and confirming that the post value is 'alias=test', the validator still returns true instead of false. I cannot ...

Beginner in CSS wanting to set background image for input field

I am working on incorporating icons into my project. The image I have contains an array of 16x16 icons at this URL: "http://www.freepbx.org/v3/browser/trunk/assets/css/jquery/vader/images/ui-icons_cd0a0a_256x240.png?rev=1" Does anyone know how I can selec ...

What is the optimal order for arranging CSS properties?

Do CSS properties need to be in a specific order? I've always organized them based on my own preference. Is there an official standard for arranging CSS properties? While server-side languages have set standards, it seems like CSS structure is more f ...

JavaScript: Utilizing variable identifiers to invoke functions

Currently, I am utilizing jQuery in my work. The app I am working on sends ajax requests to the server and receives responses in JSON format. Sometimes, the response from the server includes the name of a JavaScript function that needs to be executed. {" ...

Initiating an action the moment the element comes into view by scrolling

I need to apply specific classes to an element with an id of ig-container. The classes I want to add are: $("#ig-container").addClass("animated bounceInRight"); I aim to animate this element once it becomes visible on the screen, triggered by a user scro ...

The functionality of Ajax calls is malfunctioning specifically in Internet Explorer

I followed the cart/jquery ajax tutorial found on this codeigniter cart and jquery tutorial at nettuts+ The implementation works perfectly in all browsers except for IE. I suspect it might be related to a css selector that earlier versions of IE do not su ...

Various instances of the jQuery niceScroll plugin

I successfully set up jQuery niceScroll on the body, but now I want different themed scrollbars on one page. Below is my code snippet: Here is my fiddle: http://jsfiddle.net/JPA4R/135/ <script> $(document).ready(function () { $("body").niceScroll ...

Form popup that closes without refreshing the page upon submission

My goal is to make this form close when the button is pressed without refreshing the page, as Ajax code will be added later. The form functions as a pop-up, so it needs to close once the button is clicked. Currently, I can click the button without a refres ...

Show two <p>'s next to each other

I am trying to arrange 2 paragraphs side by side. <p class = "firstClass">This is the first paragraph.</p> <p class = "secondClass">This is the second paragraph.</p> Result: This is the first paragraph. This is the second paragra ...

Tips on aligning a v-btn alongside v-expansion-panels on the same row

Struggling with aligning my layout. Trying to get a single set of v-expansion-panels and a v-btn in the same row, both visually centered within a card. I managed to almost achieve it in this codepen: https://codepen.io/anzuj/pen/PoPPbdw with the following ...