在这种情况下不需要CSS3,如果你知道红色div的尺寸,你可以这样做(如JSBin所示):
.orange {
background-color: orange;
margin: 0 auto;
width: 200px;
height: 200px;
position: relative;
}
.red {
background-color: red;
position: absolute;
top: 0;
left: -50px;
width: 50px;
height: 50px;
}
如果你不知道元素的维度,那么情况会变得有点棘手,因为子元素不会溢出其父元素,因此维度将始终为红色 div 维度的最大值。 在这种情况下,您将不得不稍微修改 CSS 并添加一些 jQuery 魔法,就像在另一个 JSBin 中演示的那样。
CSS
orange {
background-color: orange;
margin: 0 auto;
width: 200px;
height: 200px;
position: static;
}
.red {
background-color: red;
position: relative;
Javascript
jQuery(document).ready(function($){
var redWidth = $('.red').width();
$('.red').css('left', -redWidth);
});
更新
既然你更新了你的问题,答案也需要更新:在我的脑海中,我能想到这个解决方案(你可以看到它在工作here):
$(window).scroll(function(){
$('.red').css('top', window.pageYOffset);
});
但也许有更好的纯 CSS 解决方案。
更新 #2
好的,找到了一个更优雅的纯 CSS 解决方案,但前提是您知道居中容器的宽度。听到这个(并看到它in action):
.red {
background-color: red;
margin-left: -150px; // See note (1)
position: fixed;
top: 0;
left: 50%;
width: 50px;
height: 50px;
}
(1) 这个边距是通过将橙色元素的width 减半并加上红色元素自己的width 来计算的。如果您不知道红色的宽度,请使用上面在 Javascript 部分中解释的技巧。