2016-09-27 159 views
2

这里是我的主页的简化版本:一个固定的div,保持其父宽度?

<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

只需使用一个浮动的权利,而不是一个位置的? –

+1

但我确实希望div是固定的,所以即使在滚动时它也始终显示在屏幕上。 – Thomas

+1

你将需要使用一点的JavaScript这个和绝对定位 – Pete

回答

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>

0

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>

+1

谢谢,但我希望该div被修复,因此即使我滚动时它始终可见在屏幕上。 – Thomas

+0

DaniP有一个非常好的解决方案,唯一的考虑就是如果你改变父项的宽度,你还必须更新'.nav' max-width属性的值。 – Ryanthehouse

+0

分部使用位置:固定 – Milind

相关问题