CSS position: sticky not keeping search bar at the top of the page

I'm having trouble getting a search bar to stick at the top of a div using position: sticky. I've checked for common issues like overflow: hidden on parent elements without specified height, but that's not the problem in this case. Here's the relevant CSS:

    .container {
      background-color: white;
      box-shadow: rgba(100, 100, 111, 0.2) 0px 7px 29px 0px;
      border-radius: 1rem;
      height: 85vh;
      width: 60vw;
      overflow-y: scroll;
      overflow-x: hidden;
      margin: auto;
    }

    .search-bar {
      position: sticky;
      top: 0;
      margin: 1rem 1rem;
      padding: 0.5rem;
      font-size: 20px;
      width: 100%;
      display: block;
      outline: 0;
      border-width: 0 0 2px;
    }

Please note that .search-bar is a child element of .container. If needed, here is the JSX file (it's a react app):

    import React, { useState, useEffect } from 'react';
    import { average } from './utils/util.js';
    import Card from './components/Card/Card';

    import './App.css';

    function App() {
      const [loading, setLoading] = useState(true);
      const [query, setQuery] = useState({ name: '', tag: '' });
      const [users, setUsers] = useState([]);

      const [filteredUsers, setFilteredUsers] = useState([]);

      return (
        <div className='container'>
          <input
            className='search-bar'
            placeholder='Search by name'
            onChange={(e) => {
              setQuery({ ...query, name: e.target.value });
            }}
          />
          <input
            className='search-bar'
            placeholder='Search by tag'
            onChange={(e) => {
              setQuery({ ...query, tag: e.target.value });
            }}
          />
          {filteredUsers.map((user) => (
            <Card
              id={user.id}
              pic={user.pic}
              name={`${user.firstName} ${user.lastName}`}
              email={user.email}
              company={user.company}
              skill={user.skill}
              average={average(user.grades)}
              grades={user.grades}
              tags={user.tags}
              onTagChange={tagChange}
            />
          ))}
        </div>
      );
    }

    export default App;

Answer №1

After analyzing the situation, I attempted to replicate your problem in a controlled environment,

https://codesandbox.io/s/winter-breeze-5spod8?file=/src/styles.css

To my surprise, everything seemed to be functioning properly with your provided code. The sole modification made was the addition of two .search-bar classes and the inclusion of height within them. This adjustment was necessary due to the presence of two input elements that required stickiness, causing overlap issues when scrolling.

.container {
  background-color: white;
  box-shadow: rgba(100, 100, 111, 0.2) 0px 7px 29px 0px;
  border-radius: 1rem;
  height: 85vh;
  width: 60vw;
  overflow-y: scroll;
  overflow-x: hidden;
  margin: auto;
}

.search-bar1 {
  position: sticky;
  top: 0;
  margin: 1rem 1rem;
  padding: 0.5rem;
  font-size: 20px;
  width: 100%;
  height: 3%;
  display: block;
  outline: 0;
  border-width: 0 0 2px;
}

.search-bar2 {
  position: sticky;
  top: 5.8%;
  margin: 1rem 1rem;
  padding: 0.5rem;
  font-size: 20px;
  width: 100%;
  height: 3%;
  display: block;
  outline: 0;
  border-width: 0 0 2px;
}

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

SOLVED: NextJS restricts plugins from modifying HTML to avoid unnecessary re-rendering

My current scenario is as follows: I am in the process of developing a website using NextJS (SSR) I have a requirement to load a script that will locate a div element and insert some HTML content (scripts and iframes) within it. The issue at hand: It se ...

Utilize itextsharp to transform HTML into PDF files

When I try to convert HTML to PDF using iTextSharp, the CSS styling I apply to the webpage does not get carried over to the converted PDF file. Here is the CSS code I am using: <style type="text/css"> .cssformat { ...

Utilizing pixel values for Material-UI breakpoints rather than using the default sm, md, lg, xl options

Below is the code snippet that I am using: [theme.breakpoints.only('lg')]: {} The above code works perfectly and shifts at the desired breakpoint. However, when I implement the following: [theme.breakpoints.between('1200', '1021&a ...

Is there a way to give only the left corners of a button a rounded look?

Here is the visual representation of the button: https://i.stack.imgur.com/Bjlkp.png ...

How can you determine whether the CSS of a <div> is defined in a class or an id using JavaScript/jQuery?

Hey there, I'm currently working on dynamically changing the CSS of a website. Let's say we have a div like this: <div id="fooid" class="fooclass" ></div> The div has a class "fooclass" and an ID "fooid", and we're getting its ...

Tips for resolving the issue of a Bootstrap dropdown menu overlapping content in its vicinity

I am trying to position a Bootstrap dropdown button on the right-hand side of the page. The dropdown should cover 100% of the page's width and overlay any content when activated. However, there is a large logo on the left-hand side that I want users t ...

Place a request for the Material UI switch on the platform

I'm currently in the process of constructing a switch that gets its checked value from the data retrieved from the backend. When a user toggles it, a PUT request is sent to the backend for updating the choice. Although I've made progress on it, ...

What are the methods for storing data with Apollo?

I am currently working on a project that involves an Apollo client and server with a React application where users can log in. The mutation for the login process in the Apollo server is as follows: loginUser: async (root, args) => { const theUser ...

Is there a way to integrate Javascript code with a React component?

I need to find a way to include this block of code in just one specific React component. Any suggestions? <!-- Create a button that your customers click to complete their purchase. Customize the styling to suit your branding. --> <button sty ...

The modifications to the URL made by react-router-dom's 'useSearchParams' do not persist when adjusted through the onChange callback of the mui 'Tabs' component

One feature I am looking to implement is a tab navigation component that changes based on a specific search parameter called tab. For instance, if my URL reads as example.com?tab=test2, I want the navigation bar to highlight the item labeled test2. To ac ...

Ways to retrieve interface definition using a variable

I have an interface that organizes various states together export interface ScanFiltersStatePage1 { keywords: SensitiveInfoFileKeywordFilter categories: string[] classifications: string[] fileTypes: string[] infotypes: string[] regulations: str ...

Modifying the Inactive Tab Color in Material UI

For my application, I have a specific requirement where the active tab needs to be styled in red and the inactive tab in blue. Here is how the styling is set up: newStyle: { backgroundColor: 'red', '&$selected': { b ...

Show images from the Google Search API on a React component

I'm currently working on developing a custom image search application. The process involves a search text field where the user inputs their query, and through my Flask backend, I utilize the Google Image Search API to fetch relevant images. Upon clic ...

Changing pricing on pricing table with a click

Looking to implement a price changing button that functions similar to the one found at this LINK: If anyone knows of any JavaScript or other solution, please provide me with some guidance. Thank you in advance. ...

Resolving audio problems in JSSIP and React

I am currently utilizing jssip 3.2.10 to initiate calls within a React project. The server has been configured on Asterisk and CentOS. Although I can make calls successfully where the recipient can hear me clearly, I am unable to hear their audio or the ...

What could be causing the React Todo List to consistently delete the final item from the list?

I've been experimenting with creating a Todo List App using React Hooks. When I utilize <span>{todo}</span>, the app functions perfectly by deleting the clicked element. However, when I switch from <span>{todo}</span> to <i ...

Am I on the right track with incorporating responsiveness in my React development practices?

Seeking advice on creating a responsive page with React components. I am currently using window.matchMedia to match media queries and re-rendering every time the window size is set or changes. function reportWindowSize() { let isPhone = window.matchMed ...

What steps should I take to make the code in jsfiddle functional on my Visual Studio Code platform?

const canvasEle = document.getElementById('drawing-container'); const canvasPad = document.getElementById('pad'); const toolbar = document.getElementById('toolbar'); const context = canvasEle.getContext('2d'); const ...

There seems to be an issue with the package not running at xxx:yy in React

As I work on developing a standalone Android app using React Native, the installation of react-native-fcm has led to a persistent error message appearing: The Gradle file in my project appears as follows: // Top-level build file where you can add configu ...

Encountering issues trying to display state value retrieved from an AJAX call within componentDidMount in React

I recently implemented an AJAX call in my React application using Axios, but I am a bit confused about how to handle the response data. Here is the code snippet that I used: componentDidMount() { axios.get('https://jsonplaceholder.typicode.com/us ...