设置相对于父级具有最大宽度的固定位置div的宽度 [英] Set width of fixed positioned div relative to his parent having max-width

查看:311
本文介绍了设置相对于父级具有最大宽度的固定位置div的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有JS的解决方案?

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



我不能为添加任何其他样式.wrapper except width:100%;
我尝试使用 width:inherit 但它不适用于我,因为我有父div只有max-width。 来源

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

这里是 JsFiddle演示

推荐答案

A position:fixed 元素不再与其父元素相关。它只适用于视口的boudaries。

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

MDN定义


固定 $ b不要为元素留出空间。

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.

因此,任何<$ c都可以在屏幕的视口上移动$ c> width , max-width ,或任何固定元素不会遵守的属性。

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

EDIT

事实上,它不会继承 width width 属性。所以,尝试将子元素设置为 width:100%并继承 max-width

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

这篇关于设置相对于父级具有最大宽度的固定位置div的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆