简体   繁体   English

固定元件相对于容器的定位

[英]Fixed element positioning relative to container

For a child div if I provide position fixed, it is positioning itself relative to the parent div. 对于子div,如果我提供固定位置,则它相对于父div定位。 As per my understanding, a fixed positioned element is taken out of the flow so that it is relative to the viewport. 根据我的理解,从流中取出固定位置的元素,使其相对于视口。

My question is why child div is coming inside main div? 我的问题是为什么孩子div进入主div?

Below is my code. 下面是我的代码。

 #main { margin-left : 30px; background-color : red; width : 100px; height : 100px } #child { position : fixed; background-color : yellow; width : 50px; height : 50px; } 
 <div id="main"> <div id="child">Child Div</div> </div> 

It's not. 不是。 It just looks that way. 看起来就是那样。 Set the top property to 0 and you'll see it sticks to the top of the viewport. 将top属性设置为0 ,您将看到它停留在视口的顶部。 You just didn't move it anywhere. 您只是没有将它移到任何地方。

 #main { margin-left : 30px; background-color : red; width : 100px; height : 100px } #child { position : fixed; background-color : yellow; width : 50px; height : 50px; top:0; } 
 <div id="main"> <div id="child">Child Div</div> </div> 

Another way to see that it's actually fixed would be to add enough content after it so that you can scroll down and see that it is indeed fixed. 另一种查看其确实已修复的方法是在其后添加足够的内容,以便您向下滚动并查看其确实已修复。

 #main { margin-left: 30px; background-color: red; width: 100px; height: 100px } #child { position: fixed; background-color: yellow; width: 50px; height: 50px; } 
 <div id="main"> <div id="child">Child Div</div> </div> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM