Home > Back-end >  How To Make The Sidebar Sticky Using Vanilla JavaScript & CSS Only
How To Make The Sidebar Sticky Using Vanilla JavaScript & CSS Only

Time:09-30

I'm working on a music streaming app for that I want to make the sidebar sticky (not fixed) but after lot of research on internet and apply my method still I am failed to fix the bug. Using the "align-self: flex-start; position: sticky; top: 0;" it's working, but still there is a problem. It's working perfectly when we scroll from bottom to top but when we scroll from top to bottom it get fixed and starts scrolling when we scroll up to 50% of body. I want to fix this problem please check while scrolling from top to bottom.

NOTE: I've found some jQuery and JS plugins for sticky sidebars but the problem is that I can't use them in my project because I'm building this project entirely in vanilla JavaScript. So looking for a JS and CSS expert to help me fix this bug.

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}   

body {
    padding: 10px;
}

header {
    width: 100%;
    height: 100px;
    background-color: blue;
    color: white;
    padding: 10px 0px 0px 10px;
}

main {
    margin: auto;
    padding: 10px 0px;
    display: grid;
    grid-gap: 0px;
    grid-template-columns: 70% 30%;
}

.main-content {
    background-color: red;
    height: 2000px;
    margin-right: 5px;
    color: white;
    padding: 10px 0px 0px 10px;
}

.sidebar {
    background-color: green;
    height: 1000px;
    margin-left: 5px;
    color: white;
    padding: 10px 0px 0px 10px;
/*----- Not Working Perfectly-----*/
    align-self: flex-start;
    position: sticky;
    top: 0; 
/*----- Not Working Perfectly-----*/    
}

footer {
    width: 100%;
    height: 100px;
    background-color: blue;
    color: white;
    padding: 10px 0px 0px 10px;
}
  <body>

    <header>
        <h1>HEADER</h1>
    </header>
     
    <main>
        <section > 
            <h1>MAIN CONTENT</h1>
        </section>
        <section >
            <h1>SIDEBAR</h1>
        </section>
    </main>

    <footer>
        <h1>FOOTER</h1>
    </footer>

  </body>

CodePudding user response:

I would start by setting the height of the sidebar to 100vh, so it's always as big as the viewport. Right now it is fixed to 1000px.

 .sidebar {
  height: 100vh;
}

CodePudding user response:

Your .main-content and .sidebar shouldn't have fixed heights, their heights should depend on their content. Replace fixed heights with some text.

When using display: grid on the parent element, all their children are stretched by default (align-items: stretch), their heights depend on the child that has the largest content or height.

To avoid equal heights for children use align-items: start on the parent element or align-self: start on a specific child element (in your case .sidebar).

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

:root {
  scroll-behavior: smooth;
  --space-sm: 10px;
  --space-md: 20px;
  --space-lg: 30px;
  --space-xl: 40px;
  --text-color: #fff;
  --header-bg: blue;
  --mainContent-bg: red;
  --sidebar-bg: green;
  --footer-bg: blue;
}

body {
  display: grid;
  grid-gap: var(--space-sm);
  padding: var(--space-sm);
  color: var(--text-color);
}

header {
  padding: var(--space-sm);
  height: 100px;
  background-color: var(--header-bg);
}

main {
  display: grid;
  column-gap: var(--space-sm);
  grid-template-columns: 2fr 1fr;
  align-items: start;
}

.main-content {
  background-color: var(--mainContent-bg);
  padding: var(--space-sm);
}

.main-content p {
  margin-bottom: var(--space-md);
}


.sidebar {
  position: sticky;
  top: 0;
  padding: var(--space-sm);
  background-color: var(--sidebar-bg);
}

.sidebar li {
  list-style: none;
}

.sidebar a {
  text-decoration: none;
 }

footer {
  padding: var(--space-sm);
  height: 100px;
  background-color: var(--footer-bg);
}
 <body>
<header>
  <h1>HEADER</h1>
</header>

<main>
  <section >
    <h1>MAIN CONTENT</h1>
    <p id="paragraph1">
      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>
    <p id="paragraph2">
      Sed ut perspiciatis unde omnis iste natus error sit voluptatem
      accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae
      ab illo inventore veritatis et quasi architecto beatae vitae dicta
      sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit
      aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos
      qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui
      dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed
      quia non numquam eius modi tempora incidunt ut labore et dolore magnam
      aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum
      exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex
      ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in
      ea voluptate velit esse quam nihil molestiae consequatur, vel illum
      qui dolorem eum fugiat quo voluptas nulla pariatur?
    </p>
    <p id="paragraph3">
      But I must explain to you how all this mistaken idea of denouncing
      pleasure and praising pain was born and I will give you a complete
      account of the system, and expound the actual teachings of the great
      explorer of the truth, the master-builder of human happiness. No one
      rejects, dislikes, or avoids pleasure itself, because it is pleasure,
      but because those who do not know how to pursue pleasure rationally
      encounter consequences that are extremely painful. Nor again is there
      anyone who loves or pursues or desires to obtain pain of itself,
      because it is pain, but because occasionally circumstances occur in
      which toil and pain can procure him some great pleasure. To take a
      trivial example, which of us ever undertakes laborious physical
      exercise, except to obtain some advantage from it? But who has any
      right to find fault with a man who chooses to enjoy a pleasure that
      has no annoying consequences, or one who avoids a pain that produces
      no resultant pleasure?
    </p>
    <p id="paragraph4">
      At vero eos et accusamus et iusto odio dignissimos ducimus qui
      blanditiis praesentium voluptatum deleniti atque corrupti quos dolores
      et quas molestias excepturi sint occaecati cupiditate non provident,
      similique sunt in culpa qui officia deserunt mollitia animi, id est
      laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita
      distinctio. Nam libero tempore, cum soluta nobis est eligendi optio
      cumque nihil impedit quo minus id quod maxime placeat facere possimus,
      omnis voluptas assumenda est, omnis dolor repellendus. Temporibus
      autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe
      eveniet ut et voluptates repudiandae sint et molestiae non recusandae.
      Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis
      voluptatibus maiores alias consequatur aut perferendis doloribus
      asperiores repellat.
    </p>
    <p id="paragraph5">
      On the other hand, we denounce with righteous indignation and dislike
      men who are so beguiled and demoralized by the charms of pleasure of
      the moment, so blinded by desire, that they cannot foresee the pain
      and trouble that are bound to ensue; and equal blame belongs to those
      who fail in their duty through weakness of will, which is the same as
      saying through shrinking from toil and pain. These cases are perfectly
      simple and easy to distinguish. In a free hour, when our power of
      choice is untrammelled and when nothing prevents our being able to do
      what we like best, every pleasure is to be welcomed and every pain
      avoided. But in certain circumstances and owing to the claims of duty
      or the obligations of business it will frequently occur that pleasures
      have to be repudiated and annoyances accepted. The wise man therefore
      always holds in these matters to this principle of selection: he
      rejects pleasures to secure other greater pleasures, or else he
      endures pains to avoid worse pains.
    </p>
  </section>
  <section >
    <h1>SIDEBAR</h1>
    <ul>
      <li><a href="#paragraph1">Paragraph 1</a></li>
      <li><a href="#paragraph2">Paragraph 2</a></li>
      <li><a href="#paragraph3">Paragraph 3</a></li>
      <li><a href="#paragraph4">Paragraph 4</a></li>
      <li><a href="#paragraph5">Paragraph 5</a></li>
    </ul>
  </section>
</main>

<footer>
  <h1>FOOTER</h1>
</footer>
  </body>

Also, you don't need to explicitly declare width: 100% on header and footer elements because they are block-level elements, by default they have width: 100%.

  • Related