Yosef Weiner
Yosef Weiner

Reputation: 5751

Get div with fixed position to fill up width

I have the following setup:

<div id='sidebar'></div>
<div id='header'></div>
<div id='content'>Hello World</div>

#sidebar {
  float: left;
}
#sidebar ~ * {
  overflow: hidden;
}

This allows the #sidebar to push the #header and #content to the right, and after that, the #header and #content take up the full width.

What I'd like to do is make the header fixed to the top of the screen, such that the sidebar continues to push it to the right, but on scroll it remains at the top of the screen.

My naive attempt is simply to set #header { position: fixed }. This does not work; it causes the width of the #header to become auto calculated based on its children.

So then I add #header { width: 100% }. This is closer; the width fills the screen, but it is not pushed to the right by #sidebar. Adding float: left also doesn't help.

My restrictions are:

Can I do this with CSS without calculating the width/location of #sidebar in Javascript?

https://jsfiddle.net/vkL4s5Lz/1/

Upvotes: 2

Views: 108

Answers (1)

Yosef Weiner
Yosef Weiner

Reputation: 5751

The trick is to wrap the header in a wrapper, and then fix the header's position within the wrapper.

<div>
  <div id='header'></div>
</div>

header {
  position: fixed;
  width: 100%;
}

https://jsfiddle.net/vkL4s5Lz/2/

Upvotes: 2

Related Questions