Set width of fixed positioned div relative to his parent having max-width

后端 未结 3 1280
轻奢々
轻奢々 2021-01-02 01:24

Is there any solution without JS?

html

css

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-02 01:47

    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;
    }
    

提交回复
热议问题