MIkeMo
MIkeMo

Reputation: 362

position sticky with a 3 rows header

I have a 3 rows header and I need the middle row to be sticky, I tried using position: sticky but since it's relative to the element's parent I'm unable to achieve the result that I want.

Here's a fiddle: https://jsfiddle.net/8sczt7u1/2/

I was going for a CSS only solution but I'm well aware that this is a very particular case so I'm open to javascript as well.

Upvotes: 0

Views: 190

Answers (3)

MIkeMo
MIkeMo

Reputation: 362

So I fixed it by removing the wrapper around my 3 rows and using the <header> tag as the main row wrapper

https://jsfiddle.net/yvgLaq5f/

Upvotes: 1

Alexandr
Alexandr

Reputation: 522

Your code is working correctly. position: sticky operates within its container i.e. `header.

You can set the header height: 500px and see this.

Upvotes: -2

Alexandre Elshobokshy
Alexandre Elshobokshy

Reputation: 10922

Just add a display inline to your header tag

body {
  margin: 0;
}

.page-content {
  min-height: 200vh;
}

header {
  position: relative;
  display: inline;
}

.top-bar {
  background: blue;
  color: white;
  padding: 5px 20px;
  text-align: center;
}

.main-bar {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding: 20px;
  position: sticky;
  top: 0;
  background-color: grey;
  &__nav {
    display: flex;
    flex-direction: row;
    align-items: center;
    list-style-type: none;
    margin: 0;
    padding: 0;
    li {
      margin: 0 0 0 10px;
    }
  }
}

.promo-bar {
  background: red;
  color: white;
  padding: 5px 20px;
  text-align: center;
}
<header class="header">
  <div class="top-bar">Lorem ipsum dolor sit amet</div>
  <div class="main-bar">
    <div class="main-bar__logo">Logo</div>
    <ul class="main-bar__nav">
      <li><a href="">Link 1</a></li>
      <li><a href="">Link 2</a></li>
      <li><a href="">Link 3</a></li>
    </ul>
  </div>
  <div class="promo-bar">Lorem ipsum dolor sit amet consecur bla bla bla</div>
</header>

<div class="page-content"></div>

Upvotes: 3

Related Questions