Search code examples
htmlcsssticky

How to make a sticky div float over the rest of the page?


I have a floating menu sticky to the top of the window, and occupying only 1/4 of its width. The remaining 3/4 (as well as behind the menu's 1/4) should be occupied by the image on the next document section. However, the image initially appears below the menu, i.e. the menu is not floating as I want it to.

What I'm getting:

problem

What I want:

solution

body,ul {
  margin: 0;
  overflow-x:hidden;
}
header {
  background: green;
}
nav {
  background: #ff000080;
  width: 25vw;
  position: sticky;
  top: 0;
}
main img {
  width: 100vw;
}
<header>Title</header>
<nav>
  <ul>
    <li>link 1</li>
    <li>link 2</li>
    <li>link 3</li>
  </ul>
</nav>
<main>
  <img src='https://cdn.britannica.com/90/3890-050-F451C580/rainforest-coast-lowland-rainforests-Ecuador-tropics-evergreen.jpg' />
</main>

How do I make the sticky element float all the time, i.e. display no white space on its right side?

EDIT: The image cannot be on the background. It should be inside the main tag, where there will be more elements, including text and possibly other images. It all should scroll together, except for the menu, that must stick to the top.


Solution

  • You can consider float and shape-outside trick to make sure the element will take no space:

    body,ul {
      margin: 0;
      overflow-x:hidden;
    }
    header {
      background: green;
    }
    nav {
      background: #ff000080;
      width: 25vw;
      position: sticky;
      top: 0;
      float:left;
      shape-outside:linear-gradient(transparent,transparent);
    }
    main img {
      width: 100%;
    }
    <header>Title</header>
    <nav>
      <ul>
        <li>link 1</li>
        <li>link 2</li>
        <li>link 3</li>
      </ul>
    </nav>
    <main>
      <img src='https://cdn.britannica.com/90/3890-050-F451C580/rainforest-coast-lowland-rainforests-Ecuador-tropics-evergreen.jpg' />
    </main>

    Another idea is to consider a height:0 wrapper

    body,
    ul {
      margin: 0;
      overflow-x: hidden;
    }
    
    header {
      background: green;
    }
    
    nav {
      background: #ff000080;
      width: 25vw;
    }
    
    .nav {
      position: sticky;
      top: 0;
      float: left;
      height:0;
    }
    
    main img {
      width: 100%;
    }
    <header>Title</header>
    <div class="nav">
      <nav>
        <ul>
          <li>link 1</li>
          <li>link 2</li>
          <li>link 3</li>
        </ul>
      </nav>
    </div>
    <main>
      <img src='https://cdn.britannica.com/90/3890-050-F451C580/rainforest-coast-lowland-rainforests-Ecuador-tropics-evergreen.jpg' />
    </main>