2016-09-27 5 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プロパティの値も更新する必要があるということだけが考慮されます。 DivのCSSの使用位置のための – Ryanthehouse

+0

:固定 – Milind

関連する問題