注:ページを自分のサイトにアップロードしたので、解決が容易になることを願っています:
http://www.jasonkahl.co.uk/div-center/index.html
視差効果を使用する小さな Web サイトに取り組んでいます。
ただし、div の背景画像である最初の画像が、ユーザーが移動したときに常に画面の中央に表示されるようにしたかったのです。そこで、次のスクリプトを使用して、#second .bgと呼ばれる DIV を中央に配置しました。
<script type='text/javascript'>
function CenterItem(theItem){
var winHeight=$(window).height();
var windowMiddle=winHeight/2;
var itemMiddle=$(theItem).height()/2;
var theMiddle=windowMiddle-itemMiddle;
if(winHeight>$(theItem).height()){ //vertical
$(theItem).css('top',theMiddle);
} else {
$(theItem).css('top','0');
}
}
$(document).ready(function() {
CenterItem('#second .bg');
});
$(window).resize(function() {
CenterItem('#second .bg');
});
</script>
DIV 自体はセンタリングされていますが、背景画像はセンタリングされておらず、最終的にはそのように見えます (注: 青いボックスは div の位置です)。
スクリプトを削除すると、次のようになります。
では、背景画像を DIV の中央に配置するにはどうすればよいでしょうか。
ここで役立つ場合は、htmlでdivがどのように設定されているかです:
<div id="second">
<div class="story"><div class="bg"></div>
</div> <!--.story-->
</div> <!--#second-->
CSSは次のとおりです。
#second .bg{
background: url(images/logo.png) 50% 0 no-repeat fixed ;
height: 380px;
margin: 0 auto;
padding: 0;
position: absolute;
background-position: center center;
width: 960px;
z-index: 200;
}
ありがとうございました