12

Is there any solution without JS?

html

<div class="wrapper">
   <div class="fix"></div>
</div>

css

.wrapper {
  max-width: 500px;
  border: 1px solid red;
  height: 5500px;
  position: relative;
}


.fix {
  width: inherit;
  height: 20px;
  position:fixed;
  background: black;
}

I cant add any other styles for .wrapper except width: 100%;. I try with width: inherit but it doesn't work for me because of I have parent div with only max-width. source

Here is JsFiddle Demo

Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125
CroaToa
  • 900
  • 2
  • 14
  • 36

3 Answers3

27

A position:fixed element is not relative to its parent anymore. It respects only the viewport's boudaries.

MDN Definition:

fixed
Do not leave space for the element. Instead, position it at a specified position relative to the screen's viewport and don't move it when scrolled.

So any width, max-width, or whatever property will not be respected by the fixed element.

EDIT

In fact, it won't inherit the width because there's no width property defined on the wrapper.. So, try setting the child as width: 100% and inherit the max-width:

http://jsfiddle.net/mx6anLuu/2/

.wrapper {
    max-width: 500px;
    border: 1px solid red;
    height: 5500px;
    position: relative;
}


.fix {
    max-width: inherit;
    width: 100%;
    height: 20px;
    position:fixed;
    background: black;
}
LcSalazar
  • 16,524
  • 3
  • 37
  • 69
  • 1
    It doesn't mean that it won't inherit the `width` of parent by `inherit` value. – Hashem Qolami Sep 23 '14 at 16:19
  • 1
    @HashemQolami, that's true... The truth is that it won't inherit the `width` because there's no `width` in the parent... I've updated the answer. – LcSalazar Sep 23 '14 at 16:27
  • 2
    Works like a charm, thank you. I think you should remove this "So any width, max-width, or whatever property will not be respected by the fixed element" because it's not strictly true: if the parent has a width then setting width: inherit (not width: 100%) on the fixed position child will work fine. – Leo Nov 30 '17 at 10:56
2

there is already a width on the column, just set the width of the fixed element to inherit. no reason to complicate things.

CSS:

.col-sm-3 { width: 25%; }
.fixed-in-col { width: inherit; ... }

HTML:

<div class="col-sm-3">
    <div class="fixed-in-div">
        ...
    </div>
</div>
0

It seems there is no solution without JS. This blog post by Felipe Tadeo explains why:

https://dev.to/phillt/inherit-the-width-of-the-parent-element-when-position-fixed-is-applied

It explains the confusion around width: inherit

"Fixed positions itself relative to the viewport... whenever you inherit width (with position fixed) it will be with respect to the viewport"

Sam Henderson
  • 479
  • 5
  • 7