6

I am trying to have a header div inherit its width from its parent. The header div is position: fixed. The parent is contained inside a bootstrap container.

However, as you can see in the code I've created, it is not correctly inheriting the width of its parent - it is adding some extra width from somewhere.

This is all very annoying! Any idea how to fix this?

.category-body {
  margin-left: 17% !important;
  width: 67%;
  background-color: red;
  height: 500px;
}
.category-header {
  position: fixed;
  top: 51px;
  width: inherit;
  background-color: green;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="category-body">We are in the category-body
    <div class="category-header">We are in the category-header</div>
  </div>
</div>

http://plnkr.co/edit/yVk15RqDqAac4H2eDJQe

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Tom O'Brien
  • 1,741
  • 9
  • 45
  • 73
  • Will the parent element always have a width of `67%`? – Josh Crozier Dec 08 '15 at 17:01
  • 1
    I understand what you mean, but your concept of inheritance is a bit off the mark. When you apply `position: fixed` to an element you remove it from the document flow. The element then has no parent, so there's nothing to inherit. More details [**here**](https://developer.mozilla.org/en-US/docs/Web/CSS/position#Fixed_positioning) – Michael Benjamin Dec 08 '15 at 17:05
  • 1
    @Michael_B That's not entirely true. Even though the element is removed from the document flow, it still does inherit a width of `67%`. It just doesn't work because the percentage is relative to the viewport and not the same container as the parent. The width *is* inherited. For instance, if the parent's width was `300px`, it [would work as expected](http://plnkr.co/edit/PD7jKEGgaba06NIorJHZ?p=preview). It just won't always work with percentage-based widths. – Josh Crozier Dec 08 '15 at 17:08
  • @Josh Corzier not nescessarily - only for min-width: 1200px. For smaller screen sizes it has margin-left/right: 100px (min-width: 992) or an empty .category-body{} below that – Tom O'Brien Dec 08 '15 at 17:08

1 Answers1

3

The problem stems from using a percentage value on the parent width. Browsers seem to have a problem with this. (Tested on Chrome, FF & IE11.)

If you use pixel values the problem goes away.

Revise PLUNKR

From another answer:

It seems as though the static value (250px) can be propagated through normal inheritance. Whereas when the relative value (90%) is being used, the fixed div has already been taken out-of-flow, and now inheritance-wise, it's parent is the viewport.

Learn more here:

Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701