繁体   English   中英

保持在其父级宽度内的固定 div?

[英]A fixed div that stays within its parent's width?

这是我主页的简化版本:

<div class="main">
    <div class="content"> all the content of my website </div>
    <div class="nav"> fixed on the screen and always visible </div>
</div>

这是相应的css:

.main {
    max-width: 500px;
    height: 2000px;
    margin: auto;
    background-color: grey;
}

.nav {
    width: 100px;
    height: 100px;
    background-color: blue;
    position:fixed;
    right: 0; /* that's the issue */
}

我希望固定元素留在它的父元素内(触摸其父元素的右边缘)。 但现在它正在触摸屏幕的右边框。

知道如何解决这个问题吗? 谢谢!

你可以添加一个额外的项目来模拟主容器的属性,试试这个:

 .main { max-width: 500px; height: 2000px; margin: auto; background-color: grey; } .nav { position:fixed; max-width:500px; width:100%; } .nav > div{ width: 100px; height: 100px; background-color: blue; float:right; }
 <div class="main"> <div class="content">all the content of my website</div> <div class="nav"><div>fixed on the screen and always visible</div></div> </div>

position: fixed被描述为“元素相对于浏览器窗口定位”。 您可以使用 Javascript 来实现此效果,以下是使用 jQuery 的方法,例如:

 $(window).scroll(function() { var y = $(window).scrollTop(); $(".nav").css('top', y); });
 .main { max-width: 500px; height: 4000px; margin: auto; background-color: grey; position: relative; } .nav { width: 100px; height: 100px; background-color: red; position: absolute; right: 0; /* that's the issue */ }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="main"> <div class="content"> parent </div> <div class="nav"> fixed to parent width </div> </div>

暂无
暂无

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

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