Search code examples
csspositionsticky

Position Sticky to unnested element CSS only?


I'm trying to stick both a header bar AND a logo to the top of the page. I have the header bar working great with position:sticky but the logo resides inside of a different div which is not nested (due to other existing elements). What would I need to do to make the following LOGO also sticky?

JS Fiddle Demo

.sticky {position: sticky; top: 0; }

.header-row {
  width: 100%;
  height: 35px;
  margin-top:55px;
  color: #FFF;
  background-color: #1c1209;
  border-bottom: 1px dashed #FFF;    
}

.nav-logo-area {background-color: #076064; height: 200px; transform: none;}
.logo {  width: 111px; margin: 0 auto;}

.content-area {background-color: #ACE0D5; min-height:1200px; height: 1200px;}
<!-- TOP ROW -->        
<div class="header-row sticky">
  header row here
</div>
    
<!-- LOGO & NAV --> 
<div class="nav-logo-area">
  This height set because nav menus and other content will go here.
  <div class="logo sticky">
    <img src="https://www.freepnglogos.com/uploads/twitter-logo-png/twitter-bird-symbols-png-logo-0.png" alt="Logo" />
  </div>
</div>
    
<!-- MAIN CONTENT & BELOW -->   
<div class="content-area">
  Some main content here. Added some height to the div to we can see the scroll action.
</div>

Is this possible with CSS only? The existing layout has a TON of additional content so simply "moving" the logo div to a different location would require a lot of repositioning work so I am hoping to accomplish this with what I have here. Thank you so much.


Solution

  • Position sticky will be related to the parent element with position: relative. You need to use position: sticky on the logo with top: 0, in this way your logo will stick to its parent element.
    I added a black background to clearly show the border of the image.

    .sticky {position: sticky; top: 0; }
    
    .header-row {
      width: 100%;
      height: 35px;
      margin-top:55px;
      color: #FFF;
      background-color: #1c1209;
      border-bottom: 1px dashed #FFF;    
    }
    
    #nav-logo-area {background-color: #076064; height: 200px; transform: none; position: relative }
    .logo {  width: 111px; margin: 0 auto}
    img { width: 100%; background-color: black }
    
    .content-area {background-color: #ACE0D5; min-height:1200px; height: 1200px;}
    <!-- TOP ROW -->        
    <div class="header-row sticky">
      header row here
    </div>
        
    <!-- LOGO & NAV --> 
    <div id="nav-logo-area">
      This height set because nav menus and other content will go here.
      <div class="logo sticky">
        <img src="https://www.freepnglogos.com/uploads/twitter-logo-png/twitter-bird-symbols-png-logo-0.png" alt="Logo" />
      </div>
    </div>
        
    <!-- MAIN CONTENT & BELOW -->   
    <div style="" class="content-area">
      Some main content here. Added some height to the div to we can see the scroll action.
    </div>