这是我的主页的简化版本:
<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 */
}
我希望固定元素留在它的父级内(触及其父级的右边缘)。但是现在它正在触摸屏幕的右边界。
知道怎么解决这个问题吗?谢谢!
答案 0 :(得分:2)
您可以添加额外的项目来模拟主容器的属性,请尝试以下方法:
.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>
答案 1 :(得分:0)
position: fixed
被描述为,&#34;元素相对于浏览器窗口定位&#34;。您可以使用Javascript来实现此效果,以下是使用jQuery的方法,例如:
$(window).scroll(function() {
var y = $(window).scrollTop();
$(".nav").css('top', y);
});
&#13;
.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 */
}
&#13;
<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>
&#13;